I'm trying to make a jQuery .ajax()
call to a public web service, and I'm having trouble finding the right syntax.
I've tried several different implementations. This one:
$.ajax({
url: 'http://www.geognos.com/api/en/countries/info/all.jsonp',
dataType: "jsonp",
success: function() {
alert('JSONP call succeeded!');
}
});
It fails with the following error:
all.jsonp:1 Uncaught ReferenceError: callback is not defined
And this one:
$.ajax({
url: 'http://www.geognos.com/api/en/countries/info/all.json',
dataType: "json",
success: function() {
alert('JSON call succeeded!');
}
});
Fails with this error:
XMLHttpRequest cannot load http://www.geognos.com/api/en/countries/info/all.json. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.
I'm serving the page through my local IIS7 instance. I've also tried various combinations of $.getJSON()
with similar results. What am I missing?
Here's a JSFiddle of the above code.
UPDATE: Thought we had a solution, but I'm still getting the callback is not defined
error when doing the JSONP calls, even though the alert/log code gets called. The response URL looks like this:
http://www.geognos.com/api/en/countries/info/all.jsonp?callback=undefined&157148585
and the JSON response is wrapped like this:
callback({"StatusMsg": "OK", "Results": {"BD": {"Name": "Bangladesh", "Capital": {"DLST": "null", "TD": 6.0, "Flg": 2, "Name": "Dhaka", ...
I've found examples with the callback name added on to the end of the URL in the .ajax()
configuration, but when I try that I get the same result, only it's tacked on to the end of my query string.
This regular JSON call will not work because of same origin policy. This is what your error is telling you with: is not allowed by Access-Control-Allow-Origin
.
The correct JSONP syntax is:
$.ajax({
url: 'http://www.geognos.com/api/en/countries/info/all.jsonp',
dataType: "jsonp",
jsonpCallback: 'callback',
success: function(data) {
console.log(data);
}
});
DEMO
The correct usage is buried in the documentation for $.ajax(). Search for the jsonpCallback
option.
$.ajax({
url: 'http://www.geognos.com/api/en/countries/info/all.jsonp',
dataType: "jsonp",
jsonpCallback: function() {
alert('JSONP call succeeded!');
}
});
Fiddle: http://jsfiddle.net/gya3b/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With