← Back to Chapters

jQuery AJAX Events

⚡ jQuery AJAX Events

? Quick Overview

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.

? Key Concepts

  • Global AJAX event handlers
  • Request lifecycle awareness
  • Success and error handling
  • Loading indicators

? Syntax / Theory

AJAX events can be attached globally using $(document) or locally inside AJAX methods. They fire automatically during AJAX request execution.

? View Code Example
// Global AJAX event handlers
$(document).ajaxStart(function(){
console.log("AJAX request started");
});

$(document).ajaxStop(function(){
console.log("AJAX request completed");
});

? Code Example(s)

? View Code Example
// 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");
}
});

? Live Output / Explanation

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.

? Interactive Example

? View Code Example
// 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.

⏳ Loading...
> Event Log Ready...

? Use Cases

  • Displaying loading spinners
  • Centralized error logging
  • Performance tracking
  • Improved UX during data fetch

✅ Tips & Best Practices

  • Use global events for common behaviors
  • Handle errors gracefully
  • Avoid blocking UI during long requests
  • Keep callbacks clean and readable

? Try It Yourself

  • Create a loader using CSS and AJAX events
  • Log timestamps of AJAX start and stop
  • Simulate an error and handle it