jQuery -

AJAX Callbacks


Introduction to jQuery AJAX Callbacks

AJAX (Asynchronous JavaScript and XML) is a technique used to create fast and dynamic web pages. jQuery provides several methods for AJAX functionality, allowing you to handle the success, error, and complete events using callbacks. This tutorial covers the basics and advanced uses of jQuery AJAX callbacks with detailed examples, best practices, and useful tips.


1. Basic Usage of AJAX Callbacks

The basic usage of AJAX callbacks involves handling the success, error, and complete events using the $.ajax() method.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Basic AJAX Callbacks 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",
                    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 demonstrates how to use the $.ajax() method to handle AJAX callbacks.


2. Handling Success Callbacks

The success callback is triggered when an AJAX request completes successfully. It's a best practice to update the DOM within the success callback.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX Success Callback 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",
                    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 handle success callbacks in an AJAX request.


3. Handling Error Callbacks

The error callback is triggered when an AJAX request fails. Proper error handling improves the user experience by providing feedback.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX Error Callback 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://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>
</body>
</html>
        
    

This example demonstrates how to handle error callbacks in an AJAX request.


4. Handling Complete Callbacks

The complete callback is triggered when an AJAX request finishes, whether it succeeds or fails. It's useful for cleanup tasks.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX Complete Callback 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",
                    complete: function(){
                        console.log("Request completed");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
</body>
</html>
        
    

This example shows how to handle complete callbacks in an AJAX request.


5. Using Callback Functions

Callback functions can be defined separately and passed to the $.ajax() method. This makes the code more modular and readable.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Callback Functions Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function handleSuccess(data) {
            $("#result").html(`<p>Title: ${data.title}</p>`);
        }

        function handleError(xhr, status, error) {
            $("#result").html(`<p>Error: ${status}</p>`);
        }

        function handleComplete() {
            console.log("Request completed");
        }

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

This example demonstrates how to use separate callback functions with the $.ajax() method.


6. Best Practice: Handling Success

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 Success Callback Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function updateDOM(data) {
            $("#result").html(`<p>Title: ${data.title}</p>`);
        }

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

This example shows a best practice for handling success callbacks.


7. Best Practice: Handling Errors

Proper error handling involves displaying user-friendly messages and possibly retrying the request. Avoid ignoring errors.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice Error Callback Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function displayError(xhr, status, error) {
            $("#result").html(`<p>Error: ${status}</p>`);
        }

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

This example demonstrates a best practice for handling error callbacks.


8. Using Deferred Objects

Deferred objects provide an alternative way to handle asynchronous operations in jQuery, allowing you to chain callbacks for better readability.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Deferred Objects Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                let request = $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET"
                });

                request.done(function(data){
                    $("#result").html(`<p>Title: ${data.title}</p>`);
                });

                request.fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                });

                request.always(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 deferred objects to handle AJAX callbacks.


9. Combining Callbacks with Promises

Promises provide a way to handle asynchronous operations more effectively. jQuery's AJAX methods return a Promise-like object.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Combining Callbacks and Promises 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"
                }).done(function(data){
                    $("#result").html(`<p>Title: ${data.title}</p>`);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                }).always(function(){
                    console.log("Request completed");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to combine callbacks with promises for better asynchronous handling.



10. Best Practice: Combining Callbacks and Promises

Combining callbacks with promises can improve code readability and maintainability. Use promises to handle multiple asynchronous operations.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Combining Callbacks and Promises 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"
                }).done(function(data){
                    $("#result").html(`<p>Title: ${data.title}</p>`);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                }).always(function(){
                    console.log("Request completed");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows a best practice for combining callbacks and promises.


11. Handling Multiple AJAX Requests

When handling multiple AJAX requests, it's important to manage their callbacks effectively. Use $.when() to handle multiple deferred objects.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Multiple AJAX Requests Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.when(
                    $.ajax({
                        url: "https://jsonplaceholder.typicode.com/posts/1",
                        method: "GET"
                    }),
                    $.ajax({
                        url: "https://jsonplaceholder.typicode.com/posts/2",
                        method: "GET"
                    })
                ).done(function(response1, response2){
                    $("#result").html(`<p>Post 1: ${response1[0].title}</p><p>Post 2: ${response2[0].title}</p>`);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example demonstrates how to handle multiple AJAX requests using $.when().


12. Best Practice: Managing Multiple Requests

Managing multiple AJAX requests can be complex. It's a best practice to use $.when() and promises to handle multiple requests efficiently.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Multiple AJAX Requests Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $.when(
                    $.ajax({
                        url: "https://jsonplaceholder.typicode.com/posts/1",
                        method: "GET"
                    }),
                    $.ajax({
                        url: "https://jsonplaceholder.typicode.com/posts/2",
                        method: "GET"
                    })
                ).done(function(response1, response2){
                    $("#result").html(`<p>Post 1: ${response1[0].title}</p><p>Post 2: ${response2[0].title}</p>`);
                }).fail(function(){
                    $("#result").html("<p>An error occurred</p>");
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <div id="result"></div>
</body>
</html>
        
    

This example shows a best practice for managing multiple AJAX requests.


13. Using Global AJAX Event Handlers

jQuery provides several global AJAX event handlers that can be used to handle AJAX events across the entire application.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Global AJAX 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",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</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 global AJAX event handlers.


14. Best Practice: Using Global Handlers

Using global AJAX event handlers can simplify the management of AJAX requests and provide a centralized way to handle AJAX events.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Global 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",
                    success: function(data){
                        $("#result").html(`<p>Title: ${data.title}</p>`);
                    },
                    error: function(){
                        $("#result").html("<p>An error occurred</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 shows a best practice for using global AJAX event handlers.


15. Conclusion

jQuery AJAX callbacks provide a powerful way to handle asynchronous operations. By following best practices, you can create efficient and maintainable code. Proper error handling, using promises, and managing multiple requests are key aspects of effective AJAX usage.