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:
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:
$.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 } });