json value not fetching from localhost to angularjs frontend - json

This my javascript part i am not able to get any response from $http.get
can anyone suggest a solution
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:3000/load")
.success(function(response) {$scope.names = response;});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="data in names">
{{ data.name + ', ' + data.age }}
</li>
</ul>
</div>

From AngularJS documentation https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
No localhost:3000, just use '/load'.
No '.success', use '.then'

Try this
var Response = $http.get( $window.location.pathname + your url); //put your url here
Response.success( function ( data ) {
$scope.Names = data;
} );
Response.error( function ( data ) {
$scope.error = data;
} );

Your angular code has to change like #Dmitri Algazin has suggested. Check below code and the JS Fiddle
$http.get("http://localhost:3000/load")
.then(function(response) {$scope.names = response.data;});
JSfiddle

Related

Call angular function inside ng-repeat and return array

I searched for this but I did not get any answer as I want, please give me a solution, I want to use ng-init inside ng-repeat, ng-init should give me different response at every loop here is my HTML
<html>
<body ng-app="crmApp">
<div ng-controller="customerDetailController">
<div ng-repeat="clientDetail in client">
<p>{{clientDetail.name}}</p>
<div ng-init="seoDetails = getCustDetail(clientDetail.name)">
<p>{{seoDetails.cust_Name}}</p>
</div>
</div>
</div>
</body>
</html>
and my js is
<script>
var crmMain = angular.module('crmApp', ['ngRoute','ngMaterial']);
crmMain.controller('customerDetailController',function customerDetailController($scope, $http, customerDetailFactory,$window) {
$scope.client = [];
$scope.init = function () {
$scope.getCustomerData();
};
$scope.getCustomerData = function () {
customerDetailFactory.getCustomerDetailData().then(function
(response) {
$scope.client = response.data;
});
};
$scope.getCustDetail = function (Name) {
var custDetail = [];
custDetail = customerDetailFactory.getCustomerDetailData(Name).then(function (response) {
alert(response.data.cust_Name);
return response.data;
});
return custDetail;
};
$scope.init();
});
crmMain.factory('customerDetailFactory', ['$http', function ($http) {
var factory = {};
var url = 'phpFile/customerDetail.php';
factory.getCustomerDetailData = function (Name) {
return $http({
method: 'POST',
url: url,
data: {
'functionName': 'clientDetailPage',
'customerName': Name
}
});
};
return factory;
}]);
</script>
In inside getCustDetail function I was given alert in there it 'll show name, but I don't know why it not showing in HTML.is anything wrong I did?
I have got one solution for this, I think I have to use Promises for this, but I don't know how to use it can anyone help me in this?
You cannot use ng-init for this purpose.
You've to do the data fetching inside the controller itself. That is like,
customerDetailFactory.getCustomerDetailData()
.then(function(response) {
$scope.client = response.data;
// for each clients, fetch 'seoDetails'
$scope.client.forEach(function(client) {
customerDetailFactory.getCustomerDetailData(client.name)
.then(function (response) {
// I hope response.data contains 'cust_Name'
client.seoDetails = response.data;
})
});
});
Now, in the view, you can directly use the seoDetails property
<div ng-repeat="clientDetail in client">
<p>{{clientDetail.name}}</p>
<p>{{clientDetail.seoDetails.cust_Name}}</p>
</div>

Angularjs and Web Services

I make a web services which returns me a JSON formatted data when I use this url(http://localhost:8080/jerseyweb/crunchify/ftocservice). Now I want to get those data through Angular js but I can not get it. The code with which I try that is as follow:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.id + ', ' + x.name }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
alert("hi");
$http.get("http://localhost:8080/jerseyweb/crunchify/ftocservice")
.success(function (data, status, headers, config) {
alert("hiee"); // i can not reach at this alert
$scope.names = data;
});
});
</script>
</body>
</html>
The JSON data in http://localhost:8080/jerseyweb/crunchify/ftocservice is as following
[{"id":98.24,"name":36.8}]
There is an error in Web Services Response.....
#OPTIONS
#Path("/getsample")
public Response getOptions() {
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.build();
}
Please try this code might be it's use full :
var response = $http({
method: "GET",
url: "http://localhost:8080/jerseyweb/crunchify/ftocservice",
dataType: "json"
});
response.then(function (obj) {
$scope.names = obj.data.name;
}, function () {
alert('Error.');
});
If data comes from the API in string format then use
var objdata = JSON.parse(obj.data);
$scope.names = objdata.name;

Need Help Reading JSON object from a URL in a HTML

I am trying to create a website in where I can get a particular json object from a url and then display it on the website. The field that I am trying to display is UV_INDEX out of three fields. Nothing is being printed out. I don't even know if it is getting the json object.
<!DOCTYPE html>
<html>
<body>
<h2>EPA </h2>
<p id="demo"></p>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON').then(function(data) {
document.getElementById('UV_INDEX').innerHtml=json.result;
alert('Your Json result is: ' + json.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
</script>
</body>
</html>
I added a third-party chrome extenstion for CORS issue. But I get this error
Uncaught (in promise) ReferenceError: json is not definedmessage: "json is not defined"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
You can try using a Ajax plugin to make CORS request where the CORS headers are not being served from service.
Add Jquery library and add your installed CORS ajax scripts after that:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>
Now you can make cross origin request by just adding crossOrigin: true in your Ajax:
E.g.
$.ajax({
crossOrigin: true,
url: "http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON/",
success: function(data) {
console.log(data);
}
});
You can try putting the same URL in the below demo page to receive the Json data.
See live demo.

How to prime angular $http cache ($cacheFactory) with static JSON content?

My goal is to get $http to work on my local filesystem by caching some static JSON objects in a $cacheFactory. I wish to avoid network requests entirely and use only cached content.
The issue is that $http is making server requests regardless of the existence of cached content. My code is as follows.
Cache Factory
myApp.factory('jsonCache', function($cacheFactory){
// create new cache object
// (tried $cacheFactory.get('$http') as well, but same result)
var cache = $cacheFactory('jsonCache');
// put static value in cache
cache.put('/json/file1.json', {"key":"value"});
return cache;
});
Factory using $http
myApp.factory('AjaxFactory', function($http, jsonCache){
console.log(jsonCache.info()); // {id: 'jsonCache', size: 1}
// this will make a request to "http://localhost/json/file1.json"
// even though there is an entry for that URL in the cache object
$http.get('/json/file1.json', {cache: jsonCache}).success(/* ... */);
return { /* ... */ };
});
At this point I'm thinking it may be the format of the data I'm using in cache.put(), but unsure.
Please see demo code below, commends should help you a bit
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/state1");
//
// Now set up the states
$stateProvider.state('state1', {
url: "/state1",
template: "<h1>State1 </h1> <pre>{{cache | json}}</pre>",
controller: 'state1Ctrl'
})
.state('state2', {
url: "/state2",
template: "<h1>State2 </h1><pre>{{cache | json}}</pre>",
controller: 'state2Ctrl'
});
});
app.controller('state1Ctrl', function($scope, myCache) {
var cache = myCache.cache.get('jsonCache');
//check if cached data exist
if (cache) {
//use cached data
$scope.cache = myCache.cache.get('jsonCache');
//if not update cache
} else {
myCache.update().success(function(data) {
//set cache
myCache.cache.put('jsonCache', data.info);
console.log(myCache.cache.info());
//get cached data
$scope.cache = myCache.cache.get('jsonCache');
}).error(function() {
console.log("error");
});
}
});
app.controller('state2Ctrl', function($scope, myCache) {
var cache = myCache.cache.get('jsonCache');
if (cache) {
$scope.cache = myCache.cache.get('jsonCache');
} else {
myCache.update().success(function(data) {
myCache.cache.put('jsonCache', data.info);
console.log(myCache.cache.info());
$scope.cache = myCache.cache.get('jsonCache');
}).error(function() {
console.log("error");
});
}
});
app.factory('myCache', function($cacheFactory, $http) {
// create new cache object
var cache = $cacheFactory('jsonCache');
// put static value in cache
function update() {
alert("update")
return $http.get("https://ws.spotify.com/search/1/track.json?q=kaizers+orchestra");
}
return {
cache: cache,
update: update
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<body ng-app="app">
<div ui-view></div>
<!-- We'll also add some navigation: -->
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</body>
I was actually able to get it working as desired on this plunk http://plnkr.co/edit/x1nfjwEoJOxzZN5PUyrX?p=preview
angular.module("myApp", [])
.factory('jsonCache', function($cacheFactory) {
// create new cache object
// (tried $cacheFactory.get('$http') as well, but same result)
var cache = $cacheFactory('jsonCache');
// put static value in cache
cache.put('file1.json', {
"key": "From Cache Factory"
});
return cache;
})
.factory('jsonFactory', function($http, jsonCache) {
var get = function(url) {
return $http.get(url, {
cache: jsonCache
});
};
return {
get: get
};
})
.controller("Ctrl", function($scope, jsonFactory, jsonCache) {
$scope.cacheInfo = jsonCache.info();
jsonFactory.get('file1.json').success(function(res) {
$scope.json = res;
});
});
I think the issue with my original code was the result of one of the many 3rd party module dependencies. (doh!)
My workaround for the code as it was, was the following:
myApp.factory('jsonFactory', function($http, $q, jsonCache){
var get = function(url){
var data = jsonCache.get(url);
// if data exists in cache, wrap in promise and return
// or do regular $http get
if(data){
return $q(function(resolve, reject){ resolve(data); });
} else {
return $http.get(url);
}
};
return {
get: get
};
});

How is possible to load some setting from .json file before angular app starts

i'm building application which uses CORS requests. Each request i use get host address from a constant
angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})
And in each service i use to send request like this:
angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
var baseurl = baseUrl.server ;
$http.get(baseurl + 'document')
Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory?
I mean : how can i load something from ajax request an make it accessible to app modules
i have tried:
.run(['$rootScope', , function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
});
And tried to access it from baseUrl:
angular.module('siteApp').factory('baseUrl',function($rootScope) {
return {
server: $rootScope.HOST
But no luck - the baseUrl.server comes undefined into functions
You can use run method of angular.
var app = angular.module('plunker', []);
app.run(function($http, $rootScope){
$http.get('config.json')
.success(function(data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function(data, status, headers, config) {
// log error
alert('error');
});
})
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.$on('config-loaded', function(){
$scope.name = $rootScope.config.name;
});
});
see this plunker
If you want to do it even before the angular app starts, you can, instead of using the ng-app directive, use the bootstrap function.
From:
https://docs.angularjs.org/api/ng/function/angular.bootstrap
<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
{{greeting}}
</div>
<script src="angular.js"></script>
<script>
var app = angular.module('demo', [])
.controller('WelcomeController', function($scope) {
$scope.greeting = 'Welcome!';
});
// Do your loading of JSON here
angular.bootstrap(document, ['demo']);
</script>
</body>
</html>
You need to tell angular about data change, so modify your code something like this:
.run(['$rootScope', function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
$rootScope.$apply(); // New line
});
}])
That $apply() is needed since its a non-angular asynchronous call.
use the blow code snippet to load the json values
.run(function ($http, $rootScope) {
$http.get('launchSettings.json')
.success(function (data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function (data, status, headers, config) {
// log error
alert('error');
});
});