jQuery AJAX events allow you to track and react to different stages of an AJAX request such as when it starts, succeeds, fails, or completes. These events help in showing loaders, handling errors, and improving user experience.
AJAX events can be attached globally using $(document) or locally inside AJAX methods. They fire automatically during AJAX request execution.
// Global AJAX event handlers
$(document).ajaxStart(function(){
console.log("AJAX request started");
});
$(document).ajaxStop(function(){
console.log("AJAX request completed");
});
// AJAX request with success and error events
$.ajax({
url: "data.json",
method: "GET",
success: function(response){
console.log("Success:", response);
},
error: function(){
console.log("Error occurred");
}
});
When the request starts, ajaxStart fires. On successful response, the success callback runs. If an error occurs, the error callback is executed. After completion, ajaxStop fires.
// Show loader during AJAX calls
$(document).ajaxStart(function(){
$("#loader").show();
});
$(document).ajaxStop(function(){
$("#loader").hide();
});
This example shows and hides a loader automatically whenever any AJAX request runs.