Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery default for ajax statusCode

As far as I understand, one possibility to handle error results with ajax is the following one:

$.ajax({
    url: someUrl,
    type: 'POST',
    success: function(data) {},
    error: function(jqXHR, exception) {
        if (jqXHR.status === 0) {
            alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404) {
            alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            alert('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            alert('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            alert('Time out error.');
        } else if (exception === 'abort') {
            alert('Ajax request aborted.');
        } else {
            alert('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
});

Or use statusCode in order to make it more readable:

$.ajax({
    url: someUrl,
    type: 'POST',
    statusCode: {
        200: function(data) {
                   :
                   :
             },
        401: function() {
                   :
                   :
             },
              :
              :

My question is:
Is it possible to use statusCode and have a default fall-through for it?

like image 750
guyaloni Avatar asked May 30 '12 11:05

guyaloni


People also ask

What is AJAX call in jQuery?

jQuery ajax() Method The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

How does AJAX work in jQuery?

What About jQuery and AJAX? jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

What is contentType in AJAX?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8 , which is the default. dataType is what you're expecting back from the server: json , html , text , etc.


1 Answers

Not in the statusCode parameter. But that's because a better (and leaner) way if you want to catch everything:

complete: function(jqXHR, textStatus) {
    switch (jqXHR.status) {
        case 200:
            alert("200 received! yay!");
            break;
        case 404:
            alert("404 received! boo!");
            break;
        default:
            alert("I don't know what I just got but it ain't good!");
    }
}
like image 74
Richard Connamacher Avatar answered Oct 10 '22 01:10

Richard Connamacher