Tuesday, February 28, 2012

Ajax request returns status 0

Last week our users reported a bug that they got an alert window in their browser showing 0(zero). We traced the problem back to the following JavaScript code:
 type: "POST",         
 url: $(this).data('targetUrl'),         
 cache: false,         
 success: function(data){                 
  //Do something         
 error:function (xhr, ajaxOptions, thrownError){

The alert window shows the following message 0 and ‘undefined’.

We found out that this could happen if the ajax request is getting canceled before it completes. We could reproduce the problem if we triggered the ajax request and then immediately click on a link to navigate away from the page. jQuery throws the error event when the user navigates away from the page either by refreshing, clicking a link, or changing the URL in the browser.

We fixed the issue by introducing a global error handler for the ajax call, and inspecting the xmlHttpRequest object:

$(document).ajaxError(function(e, jqxhr, settings, exception) {
  if (jqxhr.readyState == 0 || jqxhr.status == 0) {
    return; //Skip this error


Vusile Terence Silonda said...

This was very useful to me... The minute I read it, I understood exactly what was causing the problem on my scripts. Thanks.

Ivan Talalaev said...

Many MANY THANKS!!!!!! It was very usefull for my undersdanding ajax.

Anonymous said...

Thanks..I had the same issue

Doug S said...

Whew, thanks! I had the same issue after refactoring some code and couldn't figure out why. I just ranted at myself that "nothing changed". This gave me the much needed kick in the pants to look wider.