Working with JSONP in AngularJS
Posted: | Author: Jörn | Filed under: Javascript | Tags: AngularJS, JSONP | 3 Comments »One thing that I really like in AngularJS is how easy it is to load JSONP from the server and work with the result. With just one line of code you have the JSON object “in your hand”:
$http.jsonp('https://myurl.com/getlist?callback=JSON_CALLBACK')
.success(function (data) {
$scope.jsonObject = data;
}
);
Really easy. But at first I could not make it work. The request was returning a valid JSONP response but the Javascript would throw an error:
Uncaught ReferenceError: angularcallbacks_0 is not defined
As usual the reason for this error was quite simple once I found it: When you work with JSONP you need to add the name of the callback function (aka “padding”) to the request. The JSON that comes back from the server will then be padded in a function of the name that you provided. For example:
When you request a JSON file like this:
{"key": "data"}
using JSONP:
https://myurl.com/getlist?callback=myCallback
you will get the following response:
myCallback({"key": "data"});
When you use AngularJS, the callback name must be JSON_CALLBACK.
https://myurl.com/getlist?callback=JSON_CALLBACK
AngularJS changes the callback name internally to make sure that you can use several requests simultaneously. So your response will look like this:
angular.callbacks._0({"key": "data"});
So far so good. But when I looked at the response that I got I noticed that the callback name was missing the dots. That was the reason for the Javascript error. AngularJS was expecting angular.callbacks._0 when all it got was angularcallbacks_0.
As it turned out the PHP on the server side was stripping all dots from request parameters. That was the reason why the JSONP response could not be handled by AngularJS.