Placid
Placid

Reputation: 1438

$.getJSON is not working. Why?

I can get data from ipinfo.io with $.get() as shown below:

$.get("http://ipinfo.io", function(response) {
      alert(response.city);
    }, "jsonp");

The above works. But when I try to use $.getJSON for this purpose, I don't get the data anymore. My code is:

$.getJSON(
      "http://ipinfo.io/?callback=callback?", function(response) {
        alert(response.city);
      }
    ).fail(function(){
      console.log("failed");
    });

The "?callback=callback?" part in url is instructed in the ipinfo.io documentation.

Sometimes it shows "Too many requests" which is ok. But most of the time it fails without any error. What am I doing wrong?

Upvotes: 1

Views: 3892

Answers (3)

Whatif
Whatif

Reputation: 1

old post but someone like me might be searching an answer. save your file in html or php even though the code in it might be json. afterwards, use either get or GETJSON, the latter, if you want the output to be json.

Upvotes: 0

brroshan
brroshan

Reputation: 1650

Change "http://ipinfo.io/?callback=callback?" to "http://ipinfo.io/?callback=?.

$.getJSON(
  "http://ipinfo.io/?callback=?", function(response) {
    alert(response.city);
  }
).fail(function(){
  console.log("failed");
});

Upvotes: 1

jonjitsu
jonjitsu

Reputation: 56

As per the docs

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

So change your code from callback=callback? to callback=? like so:

$.getJSON(
      "http://ipinfo.io/?callback=?", function(response) {
        alert(response.city);
      }
    ).fail(function(){
      console.log("failed");
    });

If the webservice used a different parameter than callback for the jsonp callback you would change that part accordingly. For example if your server used results= instead the url would be "http://coolwebservice.io/?results=?"

Upvotes: 0

Related Questions