HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Global AJAX Events

Global AJAX events are special handlers that trigger whenever **any** AJAX request on the entire page is performed. These are incredibly useful for tasks that should happen site-wide, such as showing a global loading spinner or a centralized error notification.


General Sequence of Events

When an AJAX request is made, these global events are fired in the following order:

Method Triggered...
ajaxStart() When the first AJAX request begins.
ajaxSend() Before each request is sent.
ajaxSuccess() Whenever a request completes successfully.
ajaxError() Whenever a request fails.
ajaxComplete() Whenever a request completes (regardless of success/failure).
ajaxStop() When all active AJAX requests have finished.

Tracking the Start and Stop

These two methods are perfect for showing and hiding a "Loading" indicator that covers the entire website.

$(document).ajaxStart(function() {
    $("#global-spinner").show();
});

$(document).ajaxStop(function() {
    $("#global-spinner").hide();
});

Handling Global Errors

Instead of writing an error: function for every single $.ajax() call, you can define one global handler to catch failures anywhere on the page.

$(document).ajaxError(function(event, xhr, settings, thrownError) {
    console.error("AJAX Error at: " + settings.url);
    $("#error-notify").text("Something went wrong! Error: " + thrownError).fadeIn();
});
Important Note: Unlike regular AJAX settings, global events MUST be attached to the document object (e.g., $(document).ajaxStart()).

Practical Example: Progress Bar

If you have several components loading data at once, you can use ajaxSend and ajaxComplete to update a loading status.

var activeRequests = 0;

$(document).ajaxSend(function() {
    activeRequests++;
    $("#status-text").text("Loading " + activeRequests + " items...");
});

$(document).ajaxComplete(function() {
    activeRequests--;
    if (activeRequests === 0) {
        $("#status-text").text("Page is up to date.");
    }
});
Pro Tip: If you have a specific request that should **not** trigger global events (like an background auto-save), set global: false in that request's $.ajax() settings.

Key Points to Remember

  • Global events monitor **every** AJAX call on the page.
  • Always attach these methods to the document element.
  • ajaxStart/ajaxStop are the standard for page-wide loaders.
  • ajaxError provides a centralized way to log or display server failures.
  • Use the global: false setting to exclude specific requests from triggering these events.