Search code examples
phpjsonangularjsjsonp

Can't get JSON from remote server with AngularJS $http.json/get


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:

  • when trying to get dynamic JSON from PHP script, I need to send a callback, which sometimes works, but the callback fires a function which is outside the scope, so it is irrelevant for my needs.
  • when trying to load JSON from a .json file (like in the example)I get errors.
  • when using $http.get I always get the cross domain security
    message.

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


Solution

  • 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.