Reputation: 2259
I'd like to detect 401 errors in AJAX calls and redirect to login.html. But I ended up writing many duplicate of code like
if (xhr.status === 401) {
location.assign('/login.html');
}
in the error
callback.
My question is, is there a way (the best way?) to handle them uniformly? Could I could inject some code into all of those Ajax calls?
Upvotes: 2
Views: 61
Reputation: 420
function myAJax(sURL,fnSuccess,fnError) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
if(xhttp.status == 200){
fnSuccess(xhttp.responseText);
}else{
fnError('Http Error',xhttp)
}
}
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
myAJax('server/url',function(data){
//success code here
},function(){
//error code here
});
Upvotes: 0
Reputation: 25537
You can use ajaxError()
for this. This event triggers when an ajax completed with error. Then you can check the status like this,
$(document).ajaxError(function (event, jqxhr, settings, exception) {
if (jqxhr.status == 401) {
location.assign('/login.html');
}
});
Upvotes: 4