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 bi
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 callback
alert('Response: ' + response);
}, function (xhr, status) { // error callback
switch(status) {
case 404:
alert('File not found');
break;
case 500:
alert('Server error');
break;
case 0:
alert('Request aborted');
break;
default:
alert('Unknown error ' + status);
}
});
};
A simple postRequest function:
function postRequest (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.