YouTip LogoYouTip

Ajax Ajaxsend

## jQuery ajaxSend() Method The `ajaxSend()` method is a global AJAX event handler in jQuery. It specifies a callback function to be executed **just before** an AJAX request is sent to the server. This method is highly useful for implementing global behaviors, such as showing a loading spinner, adding custom request headers, or logging outgoing request URLs. --- ## Syntax and Usage ### Syntax ```javascript $(document).ajaxSend(function(event, xhr, options)); ``` ### Parameter Values | Parameter | Type | Description | | :--- | :--- | :--- | | `function(event, xhr, options)` | `Function` | **Required.** The callback function to run before the AJAX request is sent. | ### Callback Function Parameters The callback function receives three arguments: * **`event`**: The jQuery Event object. * **`xhr`**: The native `XMLHttpRequest` object. This allows you to inspect or modify headers before the request goes out (e.g., using `xhr.setRequestHeader()`). * **`options`**: An object containing the configuration options used for this AJAX request (e.g., `options.url`, `options.type`, `options.data`). > **Note:** As of jQuery version 1.8, the `ajaxSend()` method should only be attached to the `document` object. Attaching it to other DOM elements will not work as expected in modern jQuery versions. --- ## Code Examples ### Example 1: Basic Usage The following example appends a message to a `
` element showing the target URL right before any AJAX request is sent: ```javascript $(document).ajaxSend(function(event, xhr, options) { $("div").append("

Requesting: " + options.url + "

"); }); ``` ### Example 2: Adding a Global Authorization Header You can use the `xhr` parameter to dynamically inject headers (such as a Bearer Token) into every outgoing AJAX request: ```javascript $(document).ajaxSend(function(event, xhr, options) { const token = localStorage.getItem("authToken"); if (token) { xhr.setRequestHeader("Authorization", "Bearer " + token); } }); ``` ### Example 3: Showing a Loading Spinner A common real-world use case is displaying a loading indicator when an AJAX request starts: ```javascript $(document).ajaxSend(function() { $("#loading-spinner").show(); }); ``` --- ## Key Considerations 1. **Global Scope:** The `ajaxSend()` method is a global handler. It will trigger for *every* AJAX request made on the page using jQuery (e.g., `$.ajax`, `$.get`, `$.post`). 2. **Disabling Globally:** If you have a specific AJAX request that should *not* trigger global handlers like `ajaxSend()`, you can set the `global` option to `false` in that specific request: ```javascript $.ajax({ url: "example.php", global: false // This prevents ajaxSend from firing for this request }); ``` 3. **Execution Order:** `ajaxSend()` runs after the request is initialized but before it is actually transmitted over the network.
← Ajax AjaxstartAjax Ajaxerror β†’