Reputation: 2027
I'm having real trouble getting remote JSON file using AngularJS from a remote server, and even when I get it, I can't find a way of using the data.
Here is the angular code:
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.json('http://remotehost.mobi/temp.json').
success(function(data){
console.log('success');
console.log(data);
}).
error(function(data, status ){
console.log('error');
console.log('status');
});
}]);
Usually what I get are just all type of errors:
I'm looking for a way to load json data from a remote server, generated dynamically by PHP,with angular JS controller and use it inside that controller.
Thanks
Upvotes: 2
Views: 5505
Reputation: 2027
Thanks for the help. I guess my issue was a bit different, that's why I post this solution.
Evantualy I have added the a new header to allow cross origin to my PHP that dynamically generates the JSON code:
header('Access-Control-Allow-Origin: *');
header('content-type: application/json; charset=utf-8');
This goes right before the function encode and returns the json. Another thing I have added is formatting the JSON before it sent back. I have found that sending the "raw" unformatted JSON back cause unexpected problems. Since PHP 5.4 you can add JSON_PRETTY_PRINT to the json_encode:
echo json_encode($data_array, JSON_PRETTY_PRINT);
In the angular code, I checked many combinations, include @Endless suggestion to use corsproxy.com, but found that after these adjustments you can simply use $http.get
.
Hope this helps if anyone encounter strange problems with this cross domain policy.
Upvotes: 1
Reputation: 37855
A example of a proxy that enables CORS is corsproxy.com
CORE is safer then jsonp cuz it has no way of executing javascript code. On the plus side you get more control over statechange/timeout/progress and abortion with CORS since its now ajax
The only risk now is do you trust corsproxy.com to read the data that are being passed through & the updown?
The only thing you have to do is replace http://
with http://www.corsproxy.com/
(don't think it works for https...)
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.json('http://www.corsproxy.com/kinneret.mobi/temp.json').
success(function(data){
console.log('success');
console.log(data);
}).
error(function(data, status ){
console.log('error');
console.log('status');
});
}]);
Upvotes: 1
Reputation: 1308
You need to change the server to allow CORS (see this) or use $http.jsonp
and change the response to JSONP format (JSON body wrapped in a callback function call).
If you do not control the remote server, you can proxy the request through your own server so that it is no longer cross-domain.
Upvotes: 3