Channels ▼
RSS

Tools

Ajax Calls in jQuery


Ajax support in jQuery is centered on a global function that is nothing more than an abstraction of the browser’s XMLHttpRequest object. In jQuery, to compose and control all aspects of your web requests, you use the ajax function. Here’s an example of how to use the function:

$.ajax(
  {
    type: "POST",
    url: "/customers/detail",
    data: "id=1234",
    success: function(response) {
      alert( response );
    }
  }
);

The ajax function gets a long list of parameters, such as type, url, data, dataType, cache and async. For further details, you can refer to the jQuery online documentation. The url parameter indicates the URL to call, whereas the type parameter refers to the HTTP verb to use. If you need to pass parameters outside the URL — for example, as the body of the packet — you can use the data parameter. The dataType parameter indicates the type of the expected response whether HTML, XML, JSON, JSONP, or perhaps script. The cache parameter as a Boolean value indicates whether you want the library to cache the response for future access to the same URL. You should note that Ajax calls are always cached by default except for when the data type is JSONP or script. Finally, the async parameter indicates whether the call has to be run asynchronously or not.

The $.ajax function supports several callbacks that are triggered at various times during the call. The beforeSend callback is invoked just before the request is sent out. The callback receives the settings of the call and represents your last chance to modify the call. The complete callback is invoked as soon as the response is received and regardless of the outcome. The callback receives a description of the HTTP status of the request and indicates whether the request completed successfully, resulted in an error, timed out, or pointed to a not modified resource. This callback is always invoked for each Ajax call but from within the callback, however, you won’t be able to access the actual response, if any.

Following the complete event, the jQuery library fires either the success or error callback depending on the success or failure of the Ajax call. The success callback receives the response sent over the wire by the server. The error callback gets a code for the type of error (timeout, parse, error) and an exception object (which provides, if possible, more details about the failure).

It should be noted that $.ajax is not simply a wrapper around the browser native XMLHttpRequest object. It does offer additional features not in the standard object but still terribly useful. The aforementioned cache and dataType properties are just a couple of examples. Another interesting example is ifModified, a Boolean property that returns success only if the response has changed since the last request.

Beyond the $.ajaxfunction, the jQuery library provides a few event handlers for global Ajax events. Once registered, such a handler will be invoked for each Ajax operation regardless of the page that triggers it. You can add handlers for the events like ajaxComplete, ajaxError, ajaxSend, ajaxStart, ajaxStop, and ajaxSuccess. Most of these handlers are self-explanatory, but a few words are worth spending for ajaxStop. Ajax operations can run in parallel as long as the maximum number of browser-allowed connections is not exceeded. When this happens, requests are queued. At the end of each Ajax operation, jQuery checks for pending requests. When no outstanding request is found, the ajaxStop event is fired. You’ll get the ajaxStop event also if the final request is canceled by returning false from within the beforeSend callback function. Note that you can have multiple handlers for each of these events. If multiple handlers are registered, then all of them are invoked in order.

In addition to the $.ajax function, jQuery counts on a few of helper functions that address specific types of requests such as requests getting a JSON response, a script file, or performing a cross-domain call. In future articles, I’ll cover all of them as well.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video