jQuery: debugging an AJAX request

AJAX requests should be always properly tested and debugged, but this is something that web developers tend to neglect. jQuery provides the powerful $.ajax() wrapper method which comes equipped with two useful methods, namely success() and error() which fire when an AJAX request is successful or has failed, respectively.

The former method doesn't imply that an AJAX request is complete. It simply means that the HTTP status returned by the server is 200, which equals to a successful request. The latter, instead, returns all the information related to an HTTP error.

For example, let's try to perform a request that points to a non-existing URL:

(function() {
    
    var BASE_URL = 'http://' + location.host + '/';
    
    var raiseAjaxError = function() {
        $.ajax({
            url: BASE_URL + 'foo.php',
            type: 'GET',
            dataType: 'text',
            success: function(data) {
                console.log('OK: ' + data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
            }
        });
    };
    
    raiseAjaxError(); // Error: NOT FOUND error [object Object]
    
})()​

The error() method returns the human format of the corresponding HTTP error (in this case is 404) plus the XMLHttpRequest object used during the request and the text information related to the HTTP status.

It's very difficult to debug an AJAX request using the jQuery's shorthand AJAX methods because these methods don't give you a full control over the request.

Back to top