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.
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. |
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();
});
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();
});
document object (e.g.,
$(document).ajaxStart()).
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.");
}
});
global: false in that
request's $.ajax() settings.