JSONP error handling with jquery.ajax
I struggled for hours yesterday to figure out why my jquery.ajax error callback wasn’t firing when using jsonp data type. Well, there is no error handling for JSONP request! This is a known limitation with jQuery, and the website doesn’t have enough documentation around it.
What happens:
After digging deep, I found this piece of information:
When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.
If it works, the success callback get called; but if not, nothing happens. It just fails silently. For example, you are not able to catch a 404 error from the cross domain server.
You got couple of workarounds though:
- jQuery ajax Timeout:
Timeout after a reasonable amount of time to fire the error callback because it might have failed silently. You may not know what the actual error (or error status) was but at least you get to handle the error. - jquery-jsonp:
Use jsonp plug-in available on GoogleCode (http://code.google.com/p/jquery-jsonp/) that provides support for error handling.
Hope that saves some time for you guys!
Subscribe to this blog