jQuery -

AJAX Setup


Introduction to jQuery AJAX Setup

jQuery provides a powerful way to set up AJAX requests globally and locally. This allows you to configure default settings for all AJAX requests and customize individual requests as needed. This tutorial covers the basics and advanced uses of jQuery AJAX setup with detailed examples, best practices, and useful tips.


1. Setting Global AJAX Defaults

jQuery allows you to set default values for AJAX requests using the $.ajaxSetup() method. This is useful for configuring common settings that apply to all AJAX requests.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Global AJAX Setup Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            contentType: "application/json",
            dataType: "json",
            timeout: 5000
        });

        $(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 $.ajaxSetup() method to set global AJAX defaults.


2. Customizing Individual AJAX Requests

While global settings are useful, you often need to customize individual AJAX requests. This can be done by overriding the global settings with specific options for each request.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Custom AJAX Request Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            contentType: "application/json",
            dataType: "json",
            timeout: 5000
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    timeout: 10000, // Custom timeout for this request
                    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 customize individual AJAX requests.


3. Setting Default Headers

You can set default headers for all AJAX requests using the $.ajaxSetup() method. This is useful for including common headers, such as authorization tokens.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Default Headers Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            headers: {
                "Authorization": "Bearer YOUR_TOKEN_HERE"
            }
        });

        $(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 set default headers for all AJAX requests.


4. Setting Default Timeout

Setting a default timeout for AJAX requests helps prevent long-running requests from affecting the user experience. This can be configured globally using the $.ajaxSetup() method.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Default Timeout Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            timeout: 5000
        });

        $(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(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 shows how to set a default timeout for AJAX requests.


5. Global AJAX Event Handlers

jQuery provides global AJAX event handlers that can be used to monitor and handle different stages of AJAX requests. These handlers can be set up using the $.ajaxSetup() method.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Global AJAX Event Handlers Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            contentType: "application/json",
            dataType: "json",
            timeout: 5000,
            beforeSend: function(){
                console.log("Request is about to be sent");
            },
            complete: function(){
                console.log("Request completed");
            },
            error: function(xhr, status, error){
                console.log("Error occurred: " + error);
            },
            success: function(data){
                console.log("Request successful: " + data.title);
            }
        });

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

This example demonstrates how to set up global AJAX event handlers.


6. Customizing AJAX Requests with Callbacks

You can customize individual AJAX requests by specifying callback functions for success, error, and complete events. This allows you to handle the response and errors for each request.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX Request 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(xhr, status, error){
                        $("#result").html(`<p>Error: ${status}</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 customize AJAX requests with callbacks.


7. Using Deferred Objects

Deferred objects provide a way to handle asynchronous operations in jQuery. They can be used to manage AJAX requests and callbacks more effectively.

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 demonstrates how to use deferred objects with AJAX requests.


8. Combining Callbacks with Promises

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

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 shows how to combine callbacks with promises for better asynchronous handling.



9. Best Practice: Setting Global Defaults

It's a best practice to set global defaults for common AJAX settings using the $.ajaxSetup() method. This ensures consistency across all AJAX requests.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Global Defaults</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            contentType: "application/json",
            dataType: "json",
            timeout: 5000,
            headers: {
                "Authorization": "Bearer YOUR_TOKEN_HERE"
            }
        });

        $(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 setting global defaults for AJAX requests.


10. Best Practice: Customizing Individual Requests

While global defaults are useful, it's important to customize individual requests as needed. This ensures that each request has the appropriate settings for its specific use case.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Custom Requests</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            contentType: "application/json",
            dataType: "json",
            timeout: 5000
        });

        $(document).ready(function(){
            $("#btn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    timeout: 10000, // Custom timeout for this request
                    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 customizing individual AJAX requests.


11. Best Practice: Handling Errors

Proper error handling involves using the error callback to display user-friendly messages and possibly retry the request. Avoid ignoring errors.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Error Handling</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 a best practice for handling errors in AJAX requests.


12. Best Practice: Using Promises

Using promises with AJAX requests helps to manage asynchronous operations more effectively. Promises provide a cleaner way to handle success, error, and complete callbacks.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Using Promises</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 using promises with AJAX requests.


13. Best Practice: Using Deferred Objects

Deferred objects provide a flexible way to handle asynchronous operations. Use deferred objects to manage complex AJAX workflows.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Best Practice: Deferred Objects</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 demonstrates a best practice for using deferred objects with AJAX requests.


14. Monitoring AJAX Requests

Monitoring AJAX requests can help in debugging and optimizing performance. Use global AJAX event handlers 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 shows how to monitor AJAX requests using global event handlers.


15. 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 demonstrates how to combine global and local AJAX event handlers.


16. Optimizing AJAX Performance

Optimize AJAX performance by setting appropriate timeouts, minimizing data payloads, and caching responses when possible. Use the $.ajaxSetup() method to set performance-related defaults.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Optimizing AJAX Performance Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            timeout: 5000,
            cache: true // Enable caching
        });

        $(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 optimize AJAX performance using global settings.


17. Handling Large Data Payloads

When dealing with large data payloads, consider using streaming or pagination techniques to improve performance. Customize individual requests to handle large data efficiently.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Handling Large Data 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",
                    method: "GET",
                    success: function(data){
                        let items = data.slice(0, 10).map(item => `<li>${item.title}</li>`).join("");
                        $("#result").html(items);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">Fetch Data</button>
    <ul id="result"></ul>
</body>
</html>
        
    

This example demonstrates how to handle large data payloads in AJAX requests.


18. Using AJAX with Authentication

When making authenticated AJAX requests, include authentication tokens in the headers. Use the $.ajaxSetup() method to set default headers for authentication.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>AJAX with Authentication Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            headers: {
                "Authorization": "Bearer YOUR_TOKEN_HERE"
            }
        });

        $(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 include authentication tokens in AJAX requests.


19. Security Best Practices

Ensure the security of AJAX requests by validating inputs, sanitizing outputs, and using HTTPS. Set security-related headers and defaults using the $.ajaxSetup() method.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Security Best Practices Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $.ajaxSetup({
            headers: {
                "Authorization": "Bearer YOUR_TOKEN_HERE"
            },
            contentType: "application/json",
            dataType: "json",
            timeout: 5000
        });

        $(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 security best practices for AJAX requests.


20. Conclusion

Proper setup and configuration of jQuery AJAX requests can greatly enhance the performance, security, and maintainability of your web applications. By following best practices and using the $.ajaxSetup() method effectively, you can ensure a smooth and efficient AJAX experience.