Reputation: 1675
I have been trying to make use of the World Bank API by performing cross domain AJAX requests on their API. As listed on their developer page, the basic call syntax would be:
http://api.worldbank.org/countries/all/indicators/SP.POP.TOTL?format=jsonP&prefix=Getdata Note: For JsonP format, 'prefix' parameter needs to be specified.
The following is the stripped down version of what I use in my code:
$.ajax({
url:'http://api.worldbank.org/countries/indicators/'+req.indicator+'?
format=jsonP',
dataType: 'jsonP',
jsonp : "prefix",
success : function(res){
console.log("Success");
console.log(res)
var count = res[0].total;
if(requestdata['per_page'] == 1){
request(req, count);
}
else{
var grid = formatResponse(res);
}
},
error : function(xhr, status, error){
console.log("Error");
console.log(xhr.statusText);
console.log(xhr.responseText);
console.log(xhr.status);
console.log(error);
}
})
However I run into this error every time by taking a sample indicator, say, SP.DYN.CDRT.IN:
Uncaught ReferenceError: jquery17209248960050754249_1390249074104 is not defined
If it helps, the console output is:
Error
success
*undefined*
200
Error {}
I guess the above reference is made to the anonymous callback used in jQuery calls. I'm clueless why isn't it working though. Any ideas?
Upvotes: 2
Views: 907
Reputation: 227290
The problem is with the API you are calling. They are incorrectly creating the JSONP response.
jQuery is passing a callback name of jQuery123456_7890
, but the API is trying to call jquery123456_7890
. Functions in JavaScript are case-sensitive. The API is wrongly converting the function name to all lower-case, no idea why.
You need to workaround this problem by telling jQuery to use an all lower-case callback name. That's what the jsonpCallback
parameter is for.
$.ajax({
url: 'http://api.worldbank.org/countries/indicators/'+req.indicator+'?format=jsonP',
dataType: 'jsonp',
jsonp: "prefix",
jsonpCallback: "jquery_"+(new Date).getTime(),
success: function(res){
console.log("Success");
console.log(res)
var count = res[0].total;
if(requestdata['per_page'] == 1){
request(req, count);
}
else{
var grid = formatResponse(res);
}
},
error: function(xhr, status, error){
console.log("Error");
console.log(xhr.statusText);
console.log(xhr.responseText);
console.log(xhr.status);
console.log(error);
}
})
Upvotes: 3