How to make a jsonp request

I have decided to give a detailed description of how to do a jsonp request so others will not run into the same troubles as I did.

myApp.factory('users', function($http) {
       return {
         getUsers: function() {
           var deferred = $q.defer();
           var url = "http://localhost/api/api/index.php/analytics/UsersPerCube?callback=JSON_CALLBACK";
         $http.get(url).success(function (data, status, headers, config) {
                console.log(data);
                deferred.resolve(data);
            }).error(function (data, status, headers, config) {
                //this always gets called
                console.log(status);
                deferred.reject(status);
            });
            return deferred.promise;

     }  

Notice that the url contains ?callback=JSON_CALLBACK. Here is a nice stackoverflow on that. Once you get the response then you’ll receive a json like the one below.

"angular.callbacks._1( {"cube":"1","points":"160"},{"cube":"2","points":"690"},{"cube":"3","points":"331"})"

Here is a nice stackoverflow on that subject

Now the one part that got me is that the server has to return the GET param, callback. Here is a good tutorial for that. http://niryariv.wordpress.com/2009/05/05/jsonp-quickly/ So the json looks like the one above.

Well, I hope this helps someone in the future.

Leave a Comment