Complete jQuery Ajax ($.ajax) Tutorial

We have already learn about Ajax (Asynchronous JavaScript and XML) in this Ajax Tutorial. We learned the basic but important concepts about how ajax works and it’s building blocks. Let’s move the discussion forward and see how to utilize the full power of ajax with jQuery to make application development easy, fast as well as effective.

$.ajax() Method

In the root of jQuery Ajax is ajax() function. This function is used to perform HTTP requests which are by default asynchronous. The syntax for using this function is:

$.ajax({name:value, name:value, ... })

The parameters specifies one or more name/value pairs for the AJAX request. Possible names/values in the table below:

Name

Value/Description

async

A Boolean value indicating whether the request should be handled asynchronous or not. Default is true. Please note that as of jQuery 1.8, the use of async: false is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

beforeSend(xhr)

A function to run before the request is sent

cache

A Boolean value indicating whether the browser should cache the requested pages. Default is true

complete(xhr,status)

A function to run when the request is finished (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

Specifies data to be sent to the server

dataFilter(data,type)

A function used to handle the raw response data of the XMLHttpRequest

dataType

The data type expected of the server response.

error(xhr,status,error)

A function to run if the request fails.

global

A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true

ifModified

A Boolean value specifying whether a request is only successful 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 a name for the callback function in a jsonp request

password

Specifies a password to be used in an HTTP access authentication request.

processData

A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true

scriptCharset

Specifies the charset for the request

success(result,status,xhr)

A function to be run when the request succeeds

timeout

The local timeout (in milliseconds) for the request

traditional

A Boolean value specifying whether or not 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 a username to be used in an HTTP access authentication request

xhr

A function used for creating the XMLHttpRequest object

For example, a sample ajax request can be like this (till version jQuery 1.7):

jqXHR (jQuery XMLHttpRequest) vs. XHR (XMLHttpRequest)

jQuery 1.8 has brought a major change in how ajax are mode through jQuery. This change is the return type of $.ajax() method. Previously till version 1.7, return type was XHR i.e. XMLHttpRequest, but from version 1.8 it’s jqXHR i.e. jQuery XMLHttpRequest.

In jQuery 1.8, library wraps the browser native XMLHttpRequest object with a superset API and return jqXHR object. jqXHR object simulates native XHR functionality as well as provides some more features e.g.

Synchronous vs. Asynchronous Communication

By default, all ajax requests sent through jQuery are async only. If you want to make sync calls (which is not recommended at all because it can cause the browser to freeze, which will create some very unhappy users) the use “async : false” parameter in function call as below:

jQuery Ajax Global Event Handlers

Apart from above 3 methods, i.e. done(), fail() or always(), jQuery has a set of global AJAX functions which you can use to listen for AJAX events across all AJAX requests sent via jQuery. Let’s walk through them:

$.ajaxSend()

The callback function registered with the ajaxSend() function is always called just before an AJAX request is sent via jQuery.

$.ajaxComplete()

Using $.ajaxSetup() to Globalize Parameters

Do you feel that passing a common set of parameters to all ajax requests is boring, you can use $.ajaxSetup() function to register it once and reuse them in all ajax calls. The $.ajaxSetup() function can be used to set options to be used for all AJAX calls, including those performed via $.ajax(), $.load(), $.get() etc.

You can set all the options in $.ajaxSetup() which can set to a $.ajax() call. e.g.

$.ajaxSetup({
type : "POST"
});

Above function will make all jQuery ajax requests from application to be HTTP POST methods by default. So anytime, you want to send a HTTP GET method, you must set it explicitly in that particular $.ajax() call like below:

$.ajax({
url : "/app-url/relative-url",
type : "GET"
});

Using $.ajaxPrefilter() to filter Ajax Requests

If you have been in server side web-development then you will acknowledge that filters are a great way to achieve certain objectives such as input values sanitation etc. Now jQuery provides this functionality in client side as well using ajaxPrefilter event. Using this function you can filter all AJAX calls before they are sent to server.

All Ajax options/parameters passed to the $.ajax() function can be changed (“filtered”) in $.ajaxPrefilter() before the request is sent. e.g. if you want that all HTTP requests sent to URLs ending with “/add” must be HTTP POST calls then you can apply the logic here.

$.load() Function

jQuery load() function loads some HTML via AJAX and inserts it into the selected element. It’ simple HTTP GET method in background which fetch some HTML from server and insert into element’s DOM.

$("#loadTarget").load("html-response.html");

You can also insert just only a part of the HTML loaded. If you append a space + jQuery selector string after the url then load() will only inserted the part of the loaded HTML matching the selector.

$("#loadTarget").load("html-response.html #someDiv");

In above example, ajax call will load HTML response from URL html-response.html and then it will execute jQuery ID selector of response for id=someDiv and then it will insert the result HTML into innerHTML of loadTarget.

If the loaded HTML contains any JavaScript it will get executed when the HTML is inserted into the target HTML element. However, if you load a fragment (URL + jQuery selector) then any JavaScript found in the loaded file is remove before the HTML is inserted.

$.getScript() Function

The $.getScript() function in jQuery loads a JavaScript file and executes it. This function uses jQuery’s underlying AJAX functions so the $.getScript() function cannot load scripts from other domains due to cross-domain restrictions. e.g.

$.getScript("js/myscript.js");

That’s all about working with ajax calls using jQuery. Feel free to drop your comments and suggestions in below comments section.

Happy Learning !!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.