jQuery API

jQuery.getJSON()

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

Description: Load JSON-encoded data from the server using a GET HTTP request.

  • version added: 1.0jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )

    urlA string containing the URL to which the request is sent.

    dataA 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.

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is an object (map), it is converted to a string and url-encoded before it is appended to the URL.

Most implementations will specify a success handler:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

This example, of course, relies on the structure of the JSON file:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

JSONP

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.

The jqXHR Object

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.getJSON() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). For convenience and consistency with the callback names used by $.ajax(), it provides .error(), .success(), and .complete() methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named $.ajax() callback.

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.getJSON(), to chain multiple .success(), .complete(), and .error() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

Examples:

Example: Loads the four most recent cat pictures from the Flickr JSONP API.

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });</script>

</body>
</html>

Demo:

Example: Load the JSON data from test.js and access a name from the returned JSON data.

$.getJSON("test.js", function(json) {
   alert("JSON Data: " + json.users[3].name);
 });

Example: Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.

$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
    alert("JSON Data: " + json.users[3].name);
    });

Support and Contributions

Need help with jQuery.getJSON() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.getJSON()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • None

    Sorry, my english is not very good.

    The Internet Explorer (in my case version 7) will cache the result.

    A trick from http://www.factory-h.com/blog/… :
    $.getJSON( ‘somescript.php’+ ‘?’ + Math.round(new Date().getTime()), function(data) {
    //some action here
    });

  • None

    Sorry, my english is not very good.

    The Internet Explorer (in my case version 7) will cache the result.

    A trick from http://www.factory-h.com/blog/… :
    $.getJSON( ‘somescript.php’+ ‘?’ + Math.round(new Date().getTime()), function(data) {
    //some action here
    });

  • Guest

    Cool, It's useful to cross site ajax.

  • abhi

    How can i call a usercontrol (.ascx) using jquery?

  • http://www.nurelm.com Paul Scarrone

    One thing that I had an issue with was the ability to detect and add a custom handler for if the getJSON request produces an error. Having a success callback just wasn't enough so I wrote a wrapper module that allows you to call either an synchronous or asynchronous getJSON request and attach your own custom success and error handlers to the call if you choose. I would post the whole code here but it would be rather lengthy. So here is the link to my blog post:
    http://www.nurelm.com/themanua…/

  • Skyeverything

    This function can NOT load json.js on chrome.

    • Dennis C

      I'm also seeing this problem – works with Firefox and Safari, but not Chrome on MacOs.

  • John Mbiddulph

    I can't get it to work?!

    here is my page: http://www.mypubspace.com/dash…

    the Jquery seems to be doing something?!

  • http://srikanthrayabhagi.blogspot.com/ Rayabhagi Srikanth

    If the server responds with the JSON String like

    {“ok” : 1, “msg” : “Uh, we had a sligh…ne here now, thank you. How are you?”}

    without the paranthesis, Firefox is giving me a invalid label error, how do I get rid of it with the callback=? in the url.

  • dblrbl

    Try setting server header: ‘Cache-Control: no-cache, must-revalidate’
    If you don’t have server access you can trick the browser to not cache the page by appending a timestamp to the end of the URL: http://server.com/?json=true&21334342134

  • joeshred

    Mike,

    I am not getting the “Accept” header set, using the current version of Json. Here is my call:

    $.getJSON(“https://api.globalgiving.org/api/public/projectservice/themes?api_key=e10c5e8e-730f-41c0-9b07-0983c94160a4&callback=?”,
    function(data){ alert(“The Data is:”+data);});

    On the serverside, (or even in Firebug) viewing the request Headers shows Accept being sent as */* only.

    I have also tried using the native $.ajax(…) call, setting the Headers expicitly to no avail.
    Can you show me a snippet of your code?

    Note: The server-side part of this is not yet enhanced to handle jsonp (with the callback param), so please do not respond to that. I am first just trying to see if I can get the request to go to the server with the correct Accept header.

    Thanks
    Steve

  • Zenna

    The returned data must be in json format. If no json api is provided then you can use the load method and just select the table of interest. You will have to do some post processing to get the actual data you want

  • Joda

    Everything in JSON doesn't have to be a string. The keys do but the values can be string, int, bool (true or false), null, array, or object.

    http://www.json.org/
    http://en.wikipedia.org/wiki/JSON

    Gilles' JSON is valid. Most likely the problem is how JQuery and JSONP work, and more specifically how Gilles is coding the response vs how JQuery/JSONP expects it…

    that is JSONP is responses are expected to be wrapped in a JS function.
    See (not me, just an article I found):
    http://blog.altosresearch.com/supporting-the-js…

    Basically what it comes down to is that Gilles' response JSON needs to be wrapped in parenthesis “(” … “)”. View the response that flckr provides to the jsonp url used in the example code.

  • Charlie

    Look at $.post()

  • Whitewizard

    please let me know too.