jQuery -

AJAX Events


Introduction to jQuery AJAX Events

jQuery provides several AJAX events that can be used to monitor and handle different stages of an AJAX request. These events help in providing a better user experience by showing loading indicators, handling errors, and more. This tutorial covers the basics and advanced uses of jQuery AJAX events with detailed examples, best practices, and useful tips.


1. Global AJAX Event Handlers

jQuery provides global AJAX event handlers that can be used to manage AJAX events across the entire application. These handlers include ajaxStart, ajaxStop, ajaxComplete, ajaxError, ajaxSuccess, and ajaxSend.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Global AJAX Events Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxStart(function(){
            $("#loading").show();
        }).ajaxStop(function(){
            $("#loading").hide();
        }).ajaxComplete(function(event, xhr, settings){
            console.log("Request completed");
        }).ajaxError(function(event, xhr, settings, error){
            $("#error").html("An error occurred: " + error);
        }).ajaxSuccess(function(event, xhr, settings){
            console.log("Request successful");
        }).ajaxSend(function(event, xhr, settings){
            console.log("Request sent");
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div id="loading" style="display:none;">Loading...</div>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
    <div id="error"></div>
</body>
</html>
        
    

This example demonstrates how to use global AJAX event handlers.


2. The ajaxStart Event

The ajaxStart event is triggered when an AJAX request is about to be sent. It can be used to show a loading indicator.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>ajaxStart Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxStart(function(){
            $("#loading").show();
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div id="loading" style="display:show;">Loading...</div>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to use the ajaxStart event to display a loading indicator.


3. The ajaxStop Event

The ajaxStop event is triggered when all AJAX requests have completed. It can be used to hide a loading indicator.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>ajaxStop Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxStop(function(){
            $("#loading").hide();
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div id="loading" style="display:none;">Loading...</div>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to use the ajaxStop event to hide a loading indicator.


4. The ajaxComplete Event

The ajaxComplete event is triggered when an AJAX request completes, whether it is successful or not. It can be used to perform cleanup actions.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>ajaxComplete Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxComplete(function(){
            console.log("Request completed");
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to use the ajaxComplete event to perform cleanup actions.


5. The ajaxError Event

The ajaxError event is triggered when an AJAX request fails. It can be used to handle errors and display error messages.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>ajaxError Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxError(function(event, xhr, settings, error){
            $("#error").html("An error occurred: " + error);
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://invalid-url.com/posts/1",
                    method: "GET",
                    error: function(xhr, status, error){
                        $("#result").html(`<p>Error: ${status}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
    <div id="error"></div>
</body>
</html>
        
    

This example demonstrates how to use the ajaxError event to handle errors.


6. The ajaxSuccess Event

The ajaxSuccess event is triggered when an AJAX request completes successfully. It can be used to handle successful responses.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>ajaxSuccess Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxSuccess(function(){
            console.log("Request successful");
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to use the ajaxSuccess event to handle successful responses.


7. The ajaxSend Event

The ajaxSend event is triggered before an AJAX request is sent. It can be used to modify the request before it is sent.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>ajaxSend Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxSend(function(){
            console.log("Request sent");
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to use the ajaxSend event to modify the request before it is sent.


8. Local AJAX Event Handlers

Local AJAX event handlers are attached to specific AJAX requests and are only triggered for those requests. These handlers include beforeSend, complete, error, success, and always.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Local AJAX Events Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    beforeSend: function(){
                        console.log("Request is about to be sent");
                    },
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    },
                    complete: function(){
                        console.log("Request completed");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to use local AJAX event handlers for a specific request.


9. Best Practice: Using ajaxStart and ajaxStop

It's a best practice to use the ajaxStart and ajaxStop events to show and hide loading indicators, ensuring a consistent user experience.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: ajaxStart and ajaxStop</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxStart(function(){
            $("#loading").show();
        }).ajaxStop(function(){
            $("#loading").hide();
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div id="loading" style="display:none;">Loading...</div>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates a best practice for using ajaxStart and ajaxStop.


10. Best Practice: Error Handling

Proper error handling involves using the ajaxError event to display user-friendly messages and possibly retry the request.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: ajaxError</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxError(function(event, xhr, settings, error){
            $("#error").html("An error occurred: " + error);
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://invalid-url.com/posts/1",
                    method: "GET",
                    error: function(xhr, status, error){
                        $("#result").html(`<p>Error: ${status}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
    <div id="error"></div>
</body>
</html>
        
    

This example shows a best practice for handling errors with the ajaxError event.


11. Best Practice: Success Handling

It's a best practice to keep the success callback function focused on updating the DOM or handling the response data. Avoid performing complex logic inside the success callback.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: ajaxSuccess</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxSuccess(function(){
            console.log("Request successful");
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates a best practice for handling successful responses with the ajaxSuccess event.


12. Best Practice: Cleanup with ajaxComplete

Use the ajaxComplete event to perform any necessary cleanup after an AJAX request completes, whether it succeeds or fails.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: ajaxComplete</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxComplete(function(){
            console.log("Request completed");
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows a best practice for using the ajaxComplete event for cleanup.


13. Monitoring AJAX Requests

Monitoring AJAX requests can help in debugging and optimizing performance. Use the ajaxSend and ajaxComplete events to log AJAX activity.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Monitoring AJAX Requests Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxSend(function(){
            console.log("Request sent");
        }).ajaxComplete(function(){
            console.log("Request completed");
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to monitor AJAX requests using the ajaxSend and ajaxComplete events.


14. Combining Global and Local Handlers

Combining global and local AJAX event handlers can provide a comprehensive way to manage AJAX requests. Use global handlers for common tasks and local handlers for request-specific tasks.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Combining Global and Local Handlers Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ajaxStart(function(){
            $("#loading").show();
        }).ajaxStop(function(){
            $("#loading").hide();
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    beforeSend: function(){
                        console.log("Local handler: Request is about to be sent");
                    },
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</p>");
                    },
                    complete: function(){
                        console.log("Local handler: Request completed");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div id="loading" style="display:none;">Loading...</div>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows how to combine global and local AJAX event handlers.


15. Conclusion

jQuery AJAX events provide powerful tools to manage and monitor AJAX requests. By following best practices, you can ensure a smooth user experience, proper error handling, and efficient performance. Combining global and local handlers allows for flexible and maintainable code.