Jeff
Jeff

Reputation: 21892

Why is this jQuery Ajax request failing?

The FCC recently made available a small set of API calls to access FCC data. In particular, I'm interested in the Consumer Broadband Test API. I'm trying to access this API through jQuery but am failing. Please let me know if I'm doing something wrong with my code or if this seems to be a problem with FCC's API.

If you visit this API request in a browser, it returns a XML response just fine: http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999

So I've tried to load this data in jQuery using various methods:

var url = "http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999";

$.ajax({
    type: "GET",
    url: url,
    success: function(data) {
        console.log("ajax: " + data);
    }
});

$.getJSON(url, function(data) {
    console.log("getJSON: " + data);
});

$.get(url, function(data) {
    console.log("get: " + data);
});

In the Firebug console, all three requests show a 200 (OK) status, but the response body is empty. Also, the resulting console.log messages are:

ajax: 
getJSON: null
get: 

Am I doing something wrong here?

Upvotes: 1

Views: 358

Answers (2)

Ken Redler
Ken Redler

Reputation: 23943

To work around the Same Origin Policy, you'll need to use JSONP. It is supported by the API. Add callback=? to the URL string in your .getJSON() call:

If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

So, something like this:

var url = "http://data.fcc.gov/api/speedtest/find?...&callback=?";
$.getJSON(url, function(data) {
  // do stuff
});

References: http://api.jquery.com/jQuery.getJSON/

Upvotes: 4

Calvin
Calvin

Reputation: 8765

You can't make cross-domain calls using AJAX. It doesn't work like that.

What you probably want to do is to have your AJAX query URL be a local script on your own server, then have that script run a request for the API url (using cURL or something).

Upvotes: 3

Related Questions