can.
can.

Reputation: 2259

How to handle AJAX errors uniformly in jQuery?

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

Answers (2)

Santanu
Santanu

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

Anoop Joshi P
Anoop Joshi P

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

Related Questions