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.

Low-Level Interface

These methods can be used to make arbitrary AJAX requests.

$.ajax()

Perform an asynchronous HTTP (AJAX) request.

$.ajax(settings)
  

Parameters
  • settings: A map of options for the request can contain the following items:

    • 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.

Return Value

The XMLHttpRequest object that was created.

Description

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',
});

Note

Even this sole required parameter can be made optional by setting a default using the $.ajaxSetup() function.

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.

Note

We must ensure that the MIME type that is reported by the web server matches our choice of dataType. In particular, xml must be declared by the server as text/xml for consistent results.

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.

Note

Rather than making requests synchronous using this option, better results can be achieved using the blockUI plug-in..

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.

$.ajaxSetup()

Sets default values for future AJAX requests.

$.ajaxSetup(settings)
  

Parameters
  • settings: A map of options for future requests. Same possible items as in $.ajax().

Return Value

None.

Description

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()},
});

Shorthand Methods

These methods perform the more common types of AJAX requests in less code.

$.get()

Loads data from the server using a GET HTTP request.

$.get(url[, data][, success])
  

Parameters
  • url: A string containing the URL to which the request is sent

  • data: (optional): A map of data that is sent with the request

  • success: (optional): A function that is executed if the request succeeds

Return Value

The XMLHttpRequest object that was created.

Description

This is a shorthand AJAX function, which is equivalent to:

$.ajax({
url: url,
data: data,
success: success
});

The callback is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response.

Most implementations will specify a success handler:

$.get('ajax/test.html', function(data) {
$('.result').html(data);
$().log('Load was performed.'),
});

This example fetches the requested HTML snippet and inserts it on the page.

$.getIfModified()

Loads data from the server using a GET HTTP request if it has changed since the last request.

$.getIfModified(url[, data][, success])
  

Parameters
  • url: A string containing the URL to which the request is sent

  • data: (optional): A map of data that is sent with the request

  • success: (optional): A function that is executed if the request succeeds

Return Value

The XMLHttpRequest object that was created.

Description

This is a shorthand AJAX function, which is equivalent to:

$.ajax({
url: url,
data: data,
success: success,
ifModified: true
});

The callback is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response.

Most implementations will specify a success handler:

$.getIfModified('ajax/test.html', function(data) {
if (data) {
$('.result').html(data);
}
$().log('Load was performed.'),
});

This example fetches the requested HTML snippet and inserts it on the page.

When the AJAX request is sent, an If-Modified-Since HTTP header is added. Web servers are supposed to honor this and omit the data if the file is unchanged. This can be exploited to save bandwidth when refreshing data from within a page.

A response that the page is not modified is still treated as a success. In this case the callback will still be executed, but no data will be available. The callback should trap for this to avoid discarding previously-fetched data.

.load()

Loads data from the server and places the returned HTML into the matched element.

.load(url[, data][, success])
  

Parameters
  • url: A string containing the URL to which the request is sent

  • data (optional): A map of data that is sent with the request

  • success (optional): A function that is executed if the request succeeds

Return Value

The jQuery object, for chaining purposes.

Description

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than a global function and it has an implicit callback function. When a successful response is detected, .load() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:

$('.result').load('ajax/test.html'),

The provided callback, if any, is executed after this post-processing has been performed:

$('.result').load('ajax/test.html', function() {
$(this).log('Load was performed.'),
});

The POST method is used if data is provided; otherwise, GET is assumed.

Note

The event handling suite also has a method named .load(). Which one is fired depends on the set of arguments passed.

.loadIfModified()

Loads data from the server, if it has changed since the last request, and places the returned HTML into the matched element.

.loadIfModified(url[, data][, success])
  

Parameters
  • url: A string containing the URL to which the request is sent

  • data: (optional): A map of data that is sent with the request

  • success: (optional): A function that is executed if the request succeeds

Return Value

The jQuery object, for chaining purposes.

Description

This method is roughly equivalent to $.getIfModified(url, data, success) except that it is a method rather than a global function and it has an implicit callback function. When a successful response is detected, .loadIfModified() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:

$('.result').loadIfModified('ajax/test.html'),

The provided callback, if any, is executed after this post-processing has been performed:

$('.result').loadIfModified('ajax/test.html', function() {
$(this).log('Load was performed.'),
});

The POST method is used if data is provided; otherwise, GET is assumed.

For more information on how the modification date checking works, see $.getIfModified().

$.post()

Loads data from the server using a POST HTTP request.

$.post(url[, data][, success])
  

Parameters
  • url: A string containing the URL to which the request is sent

  • data: (optional): A map of data that is sent with the request

  • success: (optional): A function that is executed if the request succeeds

Return Value

The XMLHttpRequest object that was created.

Description

This is a shorthand AJAX function, which is equivalent to:

$.ajax({
type: 'POST',
url: url,
data: data,
success: success
});

The callback is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response.

Most implementations will specify a success handler:

$.post('ajax/test.html', function(data) {
$('.result').html(data);
$().log('Load was performed.'),
});

This example fetches the requested HTML snippet and inserts it on the page.

Pages fetched with POST are never cached, so the ifModified option has no effect on these requests.

$.getJSON()

Loads JSON-encoded data from the server using a GET HTTP request.

$.getJSON(url[, data][, success])
  

Parameters
  • url: A string containing the URL to which the request is sent

  • data: (optional): A map of data that is sent with the request

  • success: (optional): A function that is executed if the request succeeds

Return Value

The XMLHttpRequest object that was created.

Description

This is a shorthand AJAX function, which is equivalent to:

$.ajax({
url: url,
dataType: 'json',
data: data,
success: success
});

The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the eval() function.

For details on the JSON format, see http://json.org/.

Most implementations will specify a success handler:

$.getJSON('ajax/test.json', function(data) {
$('.result').html('<p>' + data.foo + '</p><p>' + data.baz[1] + '</p>'),
$().log('Load was performed.'),
});

This example, of course, relies on the structure of the JSON file:

{
"foo": "The quick brown fox jumps over the lazy dog.",
"bar": "How razorback-jumping frogs can level six piqued gymnasts!",
"baz": [52, 97]
}

Using this structure, the example inserts the first string and second number from the file onto the page. If there is a syntax error in the JSON file, the request will usually fail silently; avoid frequent hand-editing of JSON data for this reason.

$.getScript()

Loads a JavaScript from the server using a GET HTTP request, and executes it.

$.getScript(url[, success])
  

Parameters
  • url: A string containing the URL to which the request is sent

  • success: (optional): A function that is executed if the request succeeds

Return Value

The XMLHttpRequest object that was created.

Descritpion

This is a shorthand AJAX function, which is equivalent to:

$.ajax({
url: url,
type: 'script',
success: success
});

The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts should have some impact on the current page:

$('.result').html('<p>Lorem ipsum dolor sit amet.</p>'),

The script can then be included and run by referencing the file name:

$.getScript('ajax/test.js', function() {
$().log('Load was performed.'),
});

In Safari, the script is not guaranteed to execute before the success callback is invoked. Practically speaking, this means that the code in the callback should not call functions or reference variables defined in the external script without at least a small delay.

Global AJAX Event Handlers

These methods register handlers to be called when certain events take place for any AJAX request on the page.

.ajaxComplete()

Registers a handler to be called when AJAX requests complete.

.ajaxComplete(handler)

Parameters
  • handler: The function to be invoked

Return Value

The jQuery object, for chaining purposes.

Description

Whenever an AJAX request completes, jQuery triggers the ajaxComplete event. All the handlers that have been registered with the .ajaxComplete() method are executed at this time.

To observe this method in action, we can set up a basic AJAX load request:

<div class="trigger button">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxComplete(function() {
$(this).log('Triggered ajaxComplete handler.'),
});

Now, we can make an AJAX request using any jQuery method:

$('.trigger').click(function() {
$('.result').load('ajax/test.html'),
});

When the user clicks the button and the AJAX request completes, the log message is displayed.

All ajaxComplete handlers are invoked, regardless of what AJAX request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).log('Triggered ajaxComplete handler for "ajax/test.html".'),
}
});

.ajaxError()

Registers a handler to be called when AJAX requests complete with an error.

.ajaxError(handler)
  

Parameters
  • handler: The function to be invoked

Return Value

The jQuery object, for chaining purposes.

Description

Whenever an AJAX request completes with an error, jQuery triggers the ajaxError event. All the handlers that have been registered with the .ajaxError() method are executed at this time.

To observe this method in action, we can set up a basic AJAX load request:

<div class="trigger button">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxError(function() {
$(this).log('Triggered ajaxError handler.'),
});

Now, we can make an AJAX request using any jQuery method:

$('.trigger').click(function() {
$('.result').load('ajax/missing.html'),
});

When the user clicks the button and the AJAX request fails, because the requested file is missing, the log message is displayed.

All ajaxError handlers are invoked, regardless of what AJAX request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an ajaxError handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. If the request failed because JavaScript raised an exception, the exception object is passed to the handler as a fourth parameter. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxError(function(e, xhr, settings, exception) {
if (settings.url == 'ajax/missing.html') {
$(this).log('Triggered ajaxError handler for "ajax/missing.html".'),
}
});

.ajaxSend()

Registers a handler to be called when AJAX requests begins.

.ajaxSend(handler)
  

Parameters
  • handler: The function to be invoked

Return Value

The jQuery object, for chaining purposes.

Description

Whenever an AJAX request is about to be sent, jQuery triggers the ajaxSend event. All the handlers that have been registered with the .ajaxSend() method are executed at this instant of time.

To observe this method in action, we can set up a basic AJAX load request:

<div class="trigger button">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxSend(function() {
$(this).log('Triggered ajaxSend handler.'),
});

Now, we can make an AJAX request using any jQuery method:

$('.trigger').click(function() {
$('.result').load('ajax/test.html'),
});

When the user clicks the button and the AJAX request is about to begin, the log message is displayed.

All ajaxSend handlers are invoked, regardless of what AJAX request is to be sent. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an ajaxSend handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxSend(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).log('Triggered ajaxSend handler for "ajax/test.html".'),
}
});

.ajaxStart()

Registers a handler to be called when the first AJAX request begins.

.ajaxStart(handler)
  

Parameters
  • handler: The function to be invoked

Return Value

The jQuery object, for chaining purposes.

Description

Whenever an AJAX request is about to be sent, jQuery checks whether there are any other outstanding AJAX requests. If none are in progress, jQuery triggers the ajaxStart event. All the handlers that have been registered with the .ajaxStart() method are executed at this instant of time.

To observe this method in action, we can set up a basic AJAX load request:

<div class="trigger button">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxStart(function() {
$(this).log('Triggered ajaxStart handler.'),
});

Now, we can make an AJAX request using any jQuery method:

$('.trigger').click(function() {
$('.result').load('ajax/test.html'),
});

When the user clicks the button and the AJAX request is sent, the log message is displayed.

.ajaxStop()

Registers a handler to be called when all AJAX requests have completed.

.ajaxStop(handler)
  

Parameters
  • handler: The function to be invoked

Return Value

The jQuery object, for chaining purposes.

Description

Whenever an AJAX request completes, jQuery checks whether there are any other outstanding AJAX requests; if none are remaining, jQuery triggers the ajaxStop event. All the handlers that have been registered with the .ajaxStop() method are executed at this instant of time.

To observe this method in action, we can set up a basic AJAX load request:

<div class="trigger button">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxStop(function() {
$(this).log('Triggered ajaxStop handler.'),
});

Now, we can make an AJAX request using any jQuery method:

$('.trigger').click(function() {
$('.result').load('ajax/test.html'),
});

When the user clicks the button and the AJAX request completes, the log message is displayed.

Note

Because .ajaxStart(), .ajaxStop(), .ajaxSend(), ajaxError(), and .ajaxComplete() are implemented as a methods rather than global functions, we can use the keyword this as we do here to refer to the selected elements within the callback function.

.ajaxSuccess()

Registers a handler to be called when AJAX requests are successfully completed.

.ajaxSuccess(handler)
  

Parameters
  • handler: The function to be invoked

Return Value

The jQuery object, for chaining purposes.

Description

Whenever an AJAX request is successfully completed, jQuery triggers the ajaxSuccess event. All the handlers that have been registered with the .ajaxSuccess() method are executed at this instant of time.

To observe this method in action, we can set up a basic AJAX load request:

<div class="trigger button">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxSuccess(function() {
$(this).log('Triggered ajaxSuccess handler.'),
});

Now, we can make an AJAX request using any jQuery method:

$('.trigger').click(function() {
$('.result').load('ajax/test.html'),
});

When the user clicks the button and the AJAX request successfully completes, the log message is displayed.

Note

Because .ajaxSuccess() is implemented as a method rather than a global function, we can use the this keyword as we do here to refer to the selected elements within the callback function.

All ajaxSuccess handlers are invoked, regardless of what AJAX request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an ajaxSuccess handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, we can restrict our callback only to handling events dealing with a particular URL:

$('.log').ajaxSuccess(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).log('Triggered ajaxSuccess handler for "ajax/test.html".'),
}
});

Helper Function

This function assists with common idioms encountered when performing AJAX tasks.

.serialize()

Encodes a set of form elements as a string for submission.

.serialize(param)
  

Parameters

None.

Return Value

A string containing the serialized representation of the elements.

Description

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

<form>
<div><input type="text" name="a" value="1" id="a" /></div>
<div><input type="text" name="b" value="2" id="b" /></div>
<div><input type="hidden" name="c" value="3" id="c" /></div>
<div><textarea name="d" rows="8" cols="40">4</textarea></div>
<div><select name="e">
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select></div>
<div><input type="checkbox" name="f" value="8" id="f" /></div>
<div><input type="submit" name="g" value="Submit" id="g">
</form>

We can serialize all of these element types after selecting them:

$('form').submit(function() {
$(this).log($('input, textarea, select').serialize());
return false;
});

This produces a standard-looking query string:

a=1&b=2&c=3&f=8&g=Submit&d=4&e=5

The string is close to, but not exactly the same as, the one that would be produced by the browser during a normal form submission. The .submit() method uses the .name and .value properties of each element to create the string, so in cases where these properties do not reflect the actual form values, the string can be incorrect. For example, the checkbox in the example above always has a .value of 8, whether or not the box is checked.

For a more robust solution, the form plug-in is available. Its methods provide an encoding that matches the one provided by a browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.31.159