jQuery ajax()
Method
Example
Change the text of a <div>
element using an AJAX request:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
Definition and Usage
The ajax()
method is used to perform an AJAX (asynchronous HTTP) request.
All jQuery AJAX methods use the ajax()
method. This method is typically used for requests that cannot be handled by other methods.
Syntax
The parameter specifies one or more name/value pairs for the AJAX request.
The table below lists the possible name/value pairs:
Name | Value/Description |
---|---|
async | Boolean value indicating whether the request is handled asynchronously. Default is true. |
beforeSend(xhr) | Function to run before the request is sent. |
cache | Boolean value indicating whether the browser should cache the requested page. Default is true. |
complete(xhr, status) | Function to run when the request finishes (after success and error functions). |
contentType | The content type used when sending data to the server. Default is "application/x-www-form-urlencoded". |
context | Specifies the "this" value for all AJAX-related callback functions. |
data | The data to be sent to the server. |
dataFilter(data, type) | Function to handle the raw response data of the XMLHttpRequest. |
dataType | The type of data expected from the server. |
error(xhr, status, error) | Function to run if the request fails. |
global | Boolean value indicating whether to trigger global AJAX event handlers. Default is true. |
ifModified | Boolean value indicating whether the request should succeed only if the response has changed since the last request. Default is false. |
jsonp | A string overriding the callback function in a jsonp request. |
jsonpCallback | Specifies the name of the callback function for a jsonp request. |
password | Specifies the password used in an HTTP access authentication request. |
processData | Boolean value indicating whether the data sent with the request should be converted to a query string. Default is true. |
scriptCharset | Specifies the character set of the request. |
success(result, status, xhr) | Function to run when the request succeeds. |
timeout | Sets the local timeout for the request (in milliseconds). |
traditional | Boolean value indicating whether to use the traditional style of param serialization. |
type | Specifies the type of request (GET or POST). |
url | Specifies the URL to send the request to. Default is the current page. |
username | Specifies the username used in an HTTP access authentication request. |
xhr | Function used to create the XMLHttpRequest object. |
More Examples
Generate an Asynchronous AJAX Request
Generate an AJAX Request with a Specified Data Type
Generate an AJAX Request with an Error