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.
Anonymous
Great article. I was struggling with it since morning, your blog fixed the issue :)
Anonymous
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?
Thank you!
Your article really helped me!
Thank you :)
Anonymous
Thank you so much. I was trying to get this working for a while. Adding the ‘timeout’ parameter helped!!
Winton De Shong
Ditto. Adding the ‘timeout’ parameter helped me as well. Looked all over for a solution to catch timeout/404 with JSONP. Thanks!
Prabhakar
The code that is mentioned above is not able to catch “error 500 internal server error”.
Anonymous
Nice
jQuery ajax ignores a timeout and doesn't glow a blunder event - Adrian
[…] did a small blogpost on this theme as […]