jQuery AJAX Tutorial

Learn to utilize the full power of AJAX with jQuery to make application development easy, fast as well as effective.

Table of Contents

$.ajax() Method
jqXHR (jQuery XMLHttpRequest) vs. XHR (XMLHttpRequest)
Invoking jQuery Ajax HTTP Methods
Synchronous vs. Asynchronous Communication
jQuery Ajax Global Event Handlers
	$.ajaxSend()
	$.ajaxStart()
	$.ajaxStop()
	$.ajaxSuccess()
	$.ajaxError()
	$.ajaxComplete()
Using $.ajaxSetup() to Globalize Parameters
Using $.ajaxPrefilter() to filter Ajax Requests
Other Ajax Powered Functions in jQuery
	$.get() and $.post() Functions
	$.load() Function
	$.getScript()

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

jQuery AJAX Example (below v1.8)

In the given example, we can make a sample ajax request like this (till version jQuery 1.7).

$.ajax({
	url: "/app-url/relative-url", 
	data: {
        name : "The name",
        desc : "The description"
    },
	success: function(data, textStatus, jqXHR)
	{
    	alert("Success: " + response); 
	},
	error: function(jqXHR, textStatus, errorThrown)
	{
    	alert("Error"); 
	}
});

jQuery AJAX Example (since v1.8)

In the given example, we can make a sample ajax request like this (in version jQuery 1.8 and above).

$.ajax({
    url: "/app-url/relative-url",
    data: {
        name : "The name",
        desc : "The description"
    }
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});

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.

  • It handles the HTTP request headers (Last-Modified, etag, Content-Type, MIME types etc…)
  • It handles the callbacks of the request (including promise callbacks .done(), .fail() etc…)
  • It handles any pre-filters set for the request
  • It handles any timeouts set for the request
  • It handles any cross domain calls (including jsonp)
The jqXHR objects returned by $.ajax() implement the Promise interface. The object has all the properties, methods, and behavior of a Promise.

jQuery library writers have made efforts to make it backward compatible yet it does no support onreadystatechange() method.

Invoking HTTP Methods

Let’s see how different HTTP methods can be invoked by jQuery ajax. I am just writing the skeleton of code, you are expected to change the code as per your needs.

jQuery Ajax HTTP GET or DELETE Method

$.ajax({
    url: "/app-url/relative-url",
    type: "GET", //Or "DELETE" for http delete calls
    dataType: 'json',    
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});

jQuery Ajax HTTP POST or PUT Method

$.ajax({
    url: "/app-url/relative-url",
    type: "POST", //Use "PUT" for HTTP PUT methods
    dataType: 'json',   
    data: {
        key : "value",
    }
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});

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:

$.ajax({
    url: "/app-url/relative-url",
    type: "POST", 
    async: false,
    dataType: 'json',    
    data: {
        key : "value",
    }
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});
In jQuery 1.8 and later, “async : false” option is deprecated.

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.

$(document).ajaxSend(function() {
    console.log("called before each send");
});

$.ajaxStart()

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.

If $.ajax() or $.ajaxSetup() is called with the global option set to false, the ajaxStart() method will not fire.

$( document ).ajaxStart(function() {
  	$( "#loading" ).show();
});

$.ajaxStop()

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.

If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxStop() method will not fire.

$( document ).ajaxStop(function() {
  	$( "#loading" ).hide();
});

$.ajaxSuccess()

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event.

$( document ).ajaxSuccess(function( event, xhr, settings ) {
  	$( "#msg" ).append( "<li>Successful Request!</li>" );
});

$.ajaxError()

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event.

$( document ).ajaxError(function( event, xhr, settings ) {
  	$( "#msg" ).append( "<li>Failed Request!</li>" );
});

$.ajaxComplete()

Whenever an Ajax request completes, jQuery triggers the ajaxComplete event.

$( document ).ajaxComplete(function( event, xhr, settings ) {
  	$( "#msg" ).append( "<li>Request Completed !!</li>" );
});

$.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"
});

$.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 the 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.

$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if(options.url.indexOf("/add") != -1) 
    {
        options.type = "POST";
    }
});

Here parameters are:

  • options – are the request options
  • originalOptions – are the options as provided to the $.ajax() method, unmodified and, thus, without defaults from ajaxSettings
  • jqXHR – is the jqXHR object of the request

Other Ajax Powered Functions in jQuery

Let’s go through other useful functions provided by the jQuery library using ajax internally, and can be used directly.

$.get() and $.post() Functions

jQuery has these functions which can be used to send simplified HTTP GET and HTTP POST requests. Here is an example showing how to use jQuery’s $.get() function:

var parameters = { p1 : "val1", p2 : "val2"};
$.get( "/app/url", parameters )
.done(function(data) {
    $("#label").html(data);
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

Similarily you can use $.post() function to make HTTP POST request.

var parameters = { p1 : "val1", p2 : "val2"};
$.post( "/app/url", parameters )
.done(function(data) {
    $("#label").html(data);
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

$.load() Function

jQuery load() function loads some HTML via AJAX and inserts it into the selected element. It’ a simple HTTP GET method in the background which fetches some HTML from server and insert it 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 removed 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 the below comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.