jQuery.ajax() dataType: JSONP–Error Handler Not Called

I am tasked with using an external Web Service API from a different domain to return a JSON object using the dataType: JSONP.  

I am forced to use JSONP because it is a Cross Domain Request, and I am using an Unobtrusive JavaScript Library we host in the Azure Cloud.

Sporadically, I received an error (net::ERR_NETWORK_RESET).  There is an alternative external Web Service API from another domain that could provide similar results, but it’s reliability is potentially just as spotty.

The documentation for jQuery.ajax() specifically states in reference to the Error Handler:

Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

The ajax call just fails gracefully.  That may be a behavior acceptable to you, but I needed more.

So what is the [workaround]?

The Timeout Handler is your friend!  You can specify timeout to trigger an error callback.  It means that within the specified time frame the request should be successfully completed. Otherwise, assume it has failed:

  1: $.ajax({
  2:     ...
  3:     timeout: 5000, // a lot of time for the request to be successfully completed
  4:     ...
  5:     error: function(x, t, m) {
  6:         if(t==="timeout") {
  7:             // something went wrong (handle it)
  8:         }
  9:     }
 10: });

And this is where the magic begins.    Within the Error Handler, you can use a nested jQuery.ajax() call.  Who knew?!  Yes, it was a surprise to me, too.

There are two Web Services out on the Internet that both return basically the same data.  The first one is my preferred Web Service, but is sporadically subject to network timeouts and resets. 


Here is the refactored code:

  1: jQuery.ajax({
  2:     url: 'http://someurl.com/',
  3:     dataType: 'JSONP',
  4:     timeout: 5000,
  5:     error: function (x, t, m) {
  6:         jQuery.ajax({
  7:             url: 'http://anotherurl.com/',
  8:             dataType: 'JSONP',
  9:             timeout: 2000,
 10:             error: function (x, t, m) {
 11:                 // Do stuff here
 12:             }
 13:         })
 14:             .success(function (data) {
 15:                 // Do stuff here
 16:             });  // end of success for NESTED jQuery.ajax call
 17:     } // end of error for OUTER jQuery.ajax call
 18: })
 19:     .success(function (data) {
 20:                 // Do stuff here
 21:         }
 22:     }); // end of success for OUTER jQuery.ajax call


And voila!  Problem solved!

Technorati Tags: ,,,,,,,

Windows Live Tags: JSONP,Error,Handler,Cross Origin Request,Unobtrusive JavaScript,JavaScript Library,Azure,


Print | posted on Monday, March 17, 2014 4:43 PM


No comments posted yet.

Your comment:


Copyright © intermark

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski