She's out of sync
She entered through the exit
And never stopped to think
—Devo
"Out of Sync"
The AJAX capabilities in jQuery help us to load data from the server without a browser page refresh. In this chapter, we'll examine each of the available AJAX methods and functions. We'll see various ways of initiating an AJAX request, as well as several methods that can observe the requests that are in progress at any time.
These methods can be used to make arbitrary AJAX requests.
Perform an asynchronous HTTP (AJAX) request. $.ajax(settings) |
url
: A string containing the URL to which the request is sent.type
(optional): A string defining the HTTP method to use for the request (GET
or POST
). The default value is GET
.dataType
(optional): A string defining the type of data expected back from the server (xml, html, json
, or script
).ifModified
(optional): A Boolean indicating whether the server should check if the page is modified before responding to the request.timeout
(optional): Number of milliseconds after which the request will time out in failure.global
(optional): A Boolean indicating whether global AJAX event handlers will be triggered by this request. The default value is true
.beforeSend
(optional): A callback function that is executed before the request is sent.error
(optional): A callback function that is executed if the request fails.success
(optional): A callback function that is executed if the request succeeds.complete
(optional): A callback function that executes whenever the request finishes.data
(optional): A map or string that is sent to the server with the request.processData
(optional): A Boolean indicating whether to convert the submitted data from an object form into a query-string form. The default value is true
.contentType
(optional): A string containing a MIME content type to set for the request. The default value is application/x-www-form-urlencoded
.async
(optional): A Boolean indicating whether to perform the request asynchronously. The default value is true
.The $.ajax()
function underlies all AJAX requests sent by jQuery. This function is seldom directly called as several higher-level alternatives like $.post()
and .load()
are available and are easier to use. If less common options are required, though, $.ajax()
can be used for more flexibility.
At its simplest, the $.ajax()
function must atleast specify a URL from which the data is to be loaded:
$.ajax({ url: 'ajax/test.html', });
This example, using the only required option, loads the contents of the specified URL, but does nothing with the result. To use the result, we can implement one of the callback functions. The beforeSend, error, success
, and complete
options take callback functions that are invoked at the appropriate times:
beforeSend
: called before the request is sent; the XMLHttpRequest
object is passed as a parameter to it.error
: called if the request fails. The XMLHttpRequest
object is passed as a parameter as a string indicating the error type, and an exception object if applicable.success
: called if the request succeeds. The returned data is passed as the parameter to it.complete
: called when the request finishes, whether in failure or success. The XMLHttpRequest
object as well as a string containing the success or error code are passed as a parameters to it.To make use of the returned HTML, we can implement a success
handler:
$.ajax({ url: 'ajax/test.html', success: function(data) { $('.result').html(data); $().log('Load was performed.'); }, });
Such a simple example would generally be better served by using .load()
or $.get()
.
The $.ajax()
function relies on the server to provide information about the retrieved data. If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors. If another type is detected, such as HTML in the example above, the data is treated as text.
Different data handling can be achieved by using the dataType
option. Besides plain xml
, the dataType
can be html, json
, or script
. If html
is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, script
will execute the JavaScript that is pulled back from the server and return the script itself as textual data. The json
option uses eval()
to parse the fetched data file as a JavaScript object, and return the constructed object as the result data.
By default, AJAX requests are sent using the GET HTTP
method. If the POST
method is required, the method can be specified by setting a value for the type
option. This option affects how the contents of the data
option are sent to the server.
The data
option can contain either a query string of the form key1=value1&key2=value2
, or a map of the form {key1: 'value1', key2: 'value2'}
. If the latter form is used, the data is converted into a query string before it is sent. This processing can be prevented by setting processData
to false
. The processing might be undesirable if we wish to send an XML object to the server; in this case, we would also want to change the contentType
option from application/x-www-form-urlencoded
to a more appropriate MIME type.
The remaining options—ifModified, timeout, global
, and async
—are rarely required. For information on ifModified
, please refer to the $.getIfModified()
function. Request timeouts can usually be set as a global default using $.ajaxSetup()
rather than for specific requests with the timeout
option. The global
option prevents registered handlers that use .ajaxSend(), .ajaxError()
, or similar methods from firing when triggered by this request. This can be useful to, for example, suppress a loading indicator that we implemented with .ajaxSend()
if the requests are frequent and brief. Lastly, the default value for async
option is true
, indicating that the code execution can be continued after the request is made. Setting this option to false
is strongly discouraged as it can cause the browser to become unresponsive.
The $.ajax()
function returns the XMLHttpRequest
object that it creates. This can generally be discarded, but it does provide a lower-level interface for observing and manipulating the request. In particular, calling .abort()
on the object will halt the request before it completes.
Sets default values for future AJAX requests. $.ajaxSetup(settings) |
For details on the settings available for $.ajaxSetup()
, please refert to $.ajax()
. All subsequent AJAX calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup()
.
For example, we could set a default value for the URL parameter before pinging the server repeatedly:
$.ajaxSetup({ url: 'ping.php', });
Now each time an AJAX request is made, this URL will be used automatically:
$.ajax({}); $.ajax({ data: {'date': Date()}, });