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:
$.ajax({         
 type: "POST",         
 url: $(this).data('targetUrl'),         
 cache: false,         
 success: function(data){                 
  //Do something         
 },     
 error:function (xhr, ajaxOptions, thrownError){
        alert(xhr.status);             
  alert(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
  }
});

2 comments:

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.