Chapter 7. AJAX Methods

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)

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:

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:

To make use of the returned HTML, we can implement a success handler:

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.