Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajaxSetup: override error with statusCode

Tags:

jquery

ajax

I have the following code for default jQuery AJAX error handling:

$.ajaxSetup({
    error : function(jqXHR, textStatus, errorThrown) {
        alert("Error: " + textStatus + ": " + errorThrown);
    },
    statusCode : {
        404: function() {
            alert("Element not found.");
        }
    }
});

However, when 404 happens, BOTH functions are upcalled: first error, then statusCode, so I see 2 consecutive alerts.

How to prevent this behaviour and get error callback only if statusCode was not upcalled?

like image 319
weekens Avatar asked Jan 18 '12 18:01

weekens


2 Answers

How about just checking for status code 404 in your error handler?

$.ajaxSetup({
    error : function(jqXHR, textStatus, errorThrown) {
        if (jqXHR.status == 404) {
            alert("Element not found.");
        } else {
            alert("Error: " + textStatus + ": " + errorThrown);
        }
    }
});
like image 140
Garett Avatar answered Oct 22 '22 00:10

Garett


Try this:

$.ajaxSetup({
error : function(jqXHR, textStatus, errorThrown) {
    if(jqXHR.status === 404) {
      alert("Element not found.");
    } else {
      alert("Error: " + textStatus + ": " + errorThrown);
    }
}
});
like image 26
Bruce Hubbard Avatar answered Oct 22 '22 00:10

Bruce Hubbard