How to Use the jQuery ajaxComplete Method
The jQuery .ajaxComplete() method is a global event
listener that executes a callback function whenever any Ajax request
completes, regardless of whether it succeeded or failed. This article
provides a clear breakdown of what you can accomplish using
.ajaxComplete(), including hiding global loading spinners,
tracking and logging network metrics, resetting user interface states,
and executing centralized post-request cleanups across your
application.
Centralized Loading Indicators
The most common use case for .ajaxComplete() is managing
global UI indicators, such as loading spinners or progress bars. Because
it triggers on both successful completions and unexpected errors, you
can ensure that a loading overlay is hidden without having to manually
add cleanup code to every individual Ajax call.
$(document).ajaxComplete(function() {
$("#loading-spinner").hide();
});Global Request Logging and Performance Monitoring
The callback function accepts three parameters: the
event object, the XMLHttpRequest
(jqXHR) object, and the settings object used
for the request. You can use these parameters to accomplish system-wide
logging:
- Inspecting Endpoints: Determine which URL triggered
the event via
settings.url. - Logging Status Codes: Read
xhr.statusto monitor HTTP response codes (e.g., 200, 404, 500). - Auditing: Send transaction logs or execution times to an analytics service after every network request.
$(document).ajaxComplete(function(event, xhr, settings) {
console.log(`Request to ${settings.url} finished with status ${xhr.status}`);
});Re-enabling UI Elements and Form Controls
Forms frequently disable submit buttons to prevent duplicate
submissions while an Ajax request is in flight. With
.ajaxComplete(), you can globally re-enable inputs, submit
buttons, or interactive controls whenever the network activity
ceases.
$(document).ajaxComplete(function(event, xhr, settings) {
if (settings.type === "POST") {
$("button[type='submit']").prop("disabled", false);
}
});Global Session and Authentication Checks
While specific error handling is often handled by
.ajaxError(), .ajaxComplete() allows you to
inspect all completed responses for specific application-level headers
or status codes. For example, if a session expires and an API returns an
HTTP 401 Unauthorized or a custom header indicating session expiration,
you can handle the redirect logic globally in one place.
$(document).ajaxComplete(function(event, xhr) {
if (xhr.status === 401) {
window.location.href = "/login?expired=true";
}
});Resource Cleanup and State Resets
Applications that maintain internal state flags (such as
isSubmitting = true) or active timeouts can reset those
variables universally inside .ajaxComplete(). This ensures
the application state remains consistent even if an unhandled network
error occurs in a specific request.