4

I am using $.getJSON to call a url and fetch JSON data at http://jsfiddle.net/9Desk/

Although the JSON is retrieved https://i.stack.imgur.com/GE6HI.png, I am unable to execute the success function.

$(function () {
    $.getJSON(url)
    .success(function (data) {
        alert(data);
        var listItems = ""; 
    });
});​

Can anyone tell me where am I going wrong and why?

Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110
CuriousDev
  • 1,255
  • 1
  • 21
  • 44

2 Answers2

4

You need to treat the request as jsonp instead of plain json. To do so, just define the callback as callback=? instead of callback=listPlaces. From the documentation:

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.

DEMO.

João Silva
  • 89,303
  • 29
  • 152
  • 158
  • But how is it I got the JSON string back even with no callback=? in the first place. Check the screenshot in my post – CuriousDev Nov 03 '12 at 19:40
  • 1
    Another thing..the response header is Access-Control-Allow-Origin: * for my JSON call. Do I still require to give callback=? – CuriousDev Nov 03 '12 at 19:41
  • @user1089173: The request works just fine, the problem is the callback. The API you are using supports `jsonp`, which means you provide a callback (a function) to be called when the request is complete. In your example, you have `callback=listPlaces` but you don't have any function named `listPlaces`. Either define it (e.g. http://jsfiddle.net/5B88g/) and use `getScript`, or if you want to use the `done` callback, you'll have to change your url to use `callback=?` as specified in the docs. – João Silva Nov 03 '12 at 19:46
  • @user1089173: You're welcome! Also take a look at this site if you want to learn more about `jsonp` and how it works: http://json-p.org/. – João Silva Nov 03 '12 at 19:51
  • @JoãoSilva i have an issue in Jquery-TokenInput.. Please check this link and give me a solution if u can..http://stackoverflow.com/questions/13558856/what-should-be-the-correct-response-from-web-service-to-display-the-jquery-token – Xavier Nov 26 '12 at 05:42
0

From http://api.jquery.com/jQuery.getJSON/, this is the correct format for getJSON:

jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )

url: A string containing the URL to which the request is sent.

data: A map or string that is sent to the server with the request.

success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.

Pulkit Mittal
  • 5,916
  • 5
  • 21
  • 28
  • sorry but unable to determine what did I miss. Can you fit in my example to see if you get an alert? – CuriousDev Nov 03 '12 at 19:29
  • 1
    Correct, which is how he is calling it. data and success are optional, and the function returns a jqXHR object, which has the .success method which he is calling. – digitaljoel Nov 03 '12 at 19:30