AJAX will end up hitting error method when any event in page cause page load or page unload.

OCCURS:

Why this occurs is due to the ajax call in the middle of fetching data from server and the page is forcing it to close connection

SOLUTION:

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. You can detect these types of errors by by implementing an error handler for the ajax call, and inspecting the xmlHttpRequest object:


  1. if (xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)  
  2.                         return true;  // it's not really an error  
  3.                     else {  
  4.                         alert('[functionname]::' + xhr.responseText + '::[thrownerror]::' + thrownError);  
  5.                         OnError(xhr, thrownError);  
  6.                     }  
  7.   
  8. ///ERROR of ajax call  
  9.   
  10.  error: function (xmlHttpRequest, textStatus, errorThrown) {  
  11.                     if (xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)  
  12.                         return true;  // it's not really an error  
  13.                     else {  
  14.                         alert('[functionname]::' + xhr.responseText + '::[thrownerror]::' + thrownError);  
  15.                         OnError(xhr, thrownError);  
  16.                     }  
  17.                 }  

Alternative Approach:
you can check it by windows.unload event but its a function call more but more reliable
  1. var unloaded = false;  
  2. $.ajax(...) ...  
  3.  .error(function(jqXHR) {  
  4.     if (unloaded) return// Ignore errors caused by navigating away  
  5.     // Now, check for real errors ..  
  6. });  
  7. $(window).unload(function() {unloaded = true;});  

0 comments:

Post a Comment