Skip to content Skip to sidebar Skip to footer

Detect Xhr Error Is Really Due To Browser Stop Or Click To New Page

While my page is loading content via XHR, if the user clicks the stop button or clicks to go to another page, the XHR error() function is called. This wouldn't normally be a big de

Solution 1:

To distinguish between HTTP errors (404, 401, 403, 500, etc..) and request abortion errors (i.e. the user pressed Esc or navigated to other page) , you can check the XHR.status property, if the request has been aborted the status member will be zero:

document.getElementById('element').onclick = function () { 
  postRequest ('test/', null, function (response) { // success callbackalert('Response: ' + response); 
  }, function (xhr, status) { // error callbackswitch(status) { 
      case404: 
        alert('File not found'); 
        break; 
      case500: 
        alert('Server error'); 
        break; 
      case0: 
        alert('Request aborted'); 
        break; 
      default: 
        alert('Unknown error ' + status); 
    } 
  }); 
};

A simple postRequest function:

functionpostRequest(url, params, success, error) {  
  var xhr = XMLHttpRequest ? new XMLHttpRequest() : 
                             new ActiveXObject("Microsoft.XMLHTTP"); 
  xhr.open("POST", url, true); 
  xhr.onreadystatechange = function(){ 
    if ( xhr.readyState == 4 ) { 
      if ( xhr.status == 200 ) { 
    success(xhr.responseText); 
      } else { 
    error(xhr, xhr.status); 
      } 
    } 
  }; 
  xhr.onerror = function() { 
    error(xhr, xhr.status); 
  }; 
  xhr.send(params); 
} 

Run the above snippet here.

Post a Comment for "Detect Xhr Error Is Really Due To Browser Stop Or Click To New Page"