jQuery global ajax events

In the previous paragraphs, we looked at how to use callback functions to process the response from the server. But besides local functions, we can also use to handle global AJAX events. jQuery provides the following methods for handling global event data:

  • ajaxComplete: registers an AJAX request completion handler
  • ajaxError: registers a handler to be called if the request fails
  • ajaxSend: registers a function that will fire before the request is sent
  • ajaxStart: registers a handler that is fired on an ajax request
  • ajaxStop: registers a handler that is fired when ajax requests complete
  • ajaxSuccess: registers a function that is run when the request completes successfully

All methods take a handler function as a parameter. In turn, this function in all methods, except for ajaxStartand ajaxStopcan take three parameters:

an object Eventcontaining data about the event

the object jqXHRassociated with the given ajax request

Extra options

globalAn option in the ajax method is used to manage global events. By default, it is set to true, that is, global events will be generated, and we can process them. If this parameter is equal to false, then events will not be generated.

As of jquery 1.8, global events should be attached to the document:

$(function(){
    $(document).ajaxStart(function() {
        $("#log").append("<p>AjaxStart event fired</p>" );
    });
    $('button').click(function() {
        $("#result").load('ajax.php');
    });
});

When the button is clicked, an ajax request will be executed and the ajaxStart event will be triggered, as a result of which an entry about the triggered event will be added to one element, and the response from the server will be loaded into the other.

Similarly, we can use the rest of the methods:

$(document)
    .ajaxStart(function() {
        $("#log").append("<p>Request start</p>" );
    })
    .ajaxSend(function(event, jqxhr, settings) {
        $("#log").append("<p>Request sent to: "+settings.url+"</p>" );
    })
    .ajaxStop(function() {
        $("#log").append("<p>All requests completed</p>" );
    })
    .ajaxError(function(event, jqxhr, settings) {
        $("#log").append("<p>Error executing request</p>" );
    })
    .ajaxComplete(function(event, jqxhr, settings) {
        $("#log").append("<p>Request completed</p>" );
    })
    .ajaxSuccess(function(event, jqxhr, settings) {
        $("#log").append("<p>Data received from server: "+jqxhr.responseText+"</p>" );
    });
    $('button').click(function() {
        $("#result").load('ajax.php');
    });