An example of chaining jQuery Ajax request callbacks

Chaining is a great way to separate your Ajax request callbacks' code and run multiple commands/functions on one element in a row. The fail callback function is a must for finding out if anything goes wrong with the HTTP request. I recommend the below code for alerting your user of anything going wrong with a request. You can have the error posted to any notification system you have. For demo purposes, I am using the vanilla alert function. As a bonus, I have added comments to the code for explanation.

$.ajax({

    // request information goes here

}).done(function(data,textStatus,jqXHR){

    // handling of successful requests goes here
    
// please note this will not fire if there is a failed request, use the always chain for that

}).fail(function(jqXHR, exception) {

    // handling of bad requests goes here

    if (jqXHR.status === 0) {
        alert('Could not connect to the server. 0 code');
    } else if (jqXHR.status == 404) {
        alert('The requested page was not found. 404 code');
    } else if (jqXHR.status == 500) {
        alert('A Internal Server Error response. 500 code.');
    } else if (exception === 'parsererror') {
        alert('The requested JSON parse failed.');
    } else if (exception === 'timeout') {
        alert('The connection timed out.');
    } else if (exception === 'abort') {
        alert('Ajax request aborted. Try again.');
    } else {
        alert('Other Error: ' + jqXHR.responseText);
    }
    return false;

});

Comments

Popular posts from this blog

Build 6 is here

Creating hashtag hyperlinks on the fly for your website