jQuery 1.5 and JSONP requests

jQuery 1.5 adds better support for JSONP requests. As you might know, JSONP is a way to avoid the same-origin policy and do cross-domain requests by adding a method call around the JSON data.

Because browsers don’t return data from requests that fail, error handling is tricky compared to normal AJAX requests. There is a workaround by using a timer, which is the way the popular jquery.jsonp plugin solves it.

jQuery 1.5 adds this workaround, so you don’t need this plugin. All other features of the plugin, such as custom callback naming, are possible in jQuery now as well.

Here’s an example:

var req = $.ajax({
    url : url,
    dataType : "jsonp",
    timeout : 10000
});

req.success(function() {
    console.log('Yes! Success!');
});

req.error(function() {
    console.log('Oh noes!');
});

The timeout parameter is essential, because this indicates when a request should be considered ‘failed’. Because of this extra parameter you need to use $.ajax instead of $.getJSON.

The req variable contains the jqXHR object, which can be used to attach multiple callbacks and error handlers.

6 comments on “jQuery 1.5 and JSONP requests”

Add your comments »

  1. Anonymous wrote:

    Great article. I was struggling with it since morning, your blog fixed the issue :)

    Geplaatst op Tuesday 01-03-2011
  2. Anonymous wrote:

    Hey,

    I tried out your example using my serverURL. the following were the observations –

    1. the json response was visible in the net panel of the firebug plugin

    2. but in the console i was shown the following error message – “req is undefined” while accessing the req.success function

    Do I need to make any configuration on the server side for making this jsonp call?

    Geplaatst op Monday 18-04-2011
  3. Thank you! wrote:

    Your article really helped me!

    Thank you :)

    Geplaatst op Tuesday 14-06-2011
  4. Anonymous wrote:

    Thank you so much. I was trying to get this working for a while. Adding the ‘timeout’ parameter helped!!

    Geplaatst op Thursday 30-06-2011
  5. Winton De Shong wrote:

    Ditto. Adding the ‘timeout’ parameter helped me as well. Looked all over for a solution to catch timeout/404 with JSONP. Thanks!

    Geplaatst op Friday 29-07-2011
  6. Prabhakar wrote:

    The code that is mentioned above is not able to catch “error 500 internal server error”.

    Geplaatst op Thursday 29-12-2011

Leave your comments here

» An overview of all articles can be found in the archive.

Hi! I'm Hay. I make art, do projects and blog here. Read more »

Projects

More Hay at...

Archives by month