Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .ajax() calls failing

Tags:

json

jquery

ajax

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.

like image 706
Josh Earl Avatar asked Dec 17 '22 05:12

Josh Earl


2 Answers

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

like image 59
Josh Smith Avatar answered Jan 05 '23 08:01

Josh Smith


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/

like image 45
Matt Bradley Avatar answered Jan 05 '23 10:01

Matt Bradley