Asynchronous requests in jQuery

As per my last post (What is Ajax ?), we have seen that the base of each asynchronous request is XmlHttpRequest object.

Now, Let’s look at the equivalent jQuery code for make synchronous and asynchronous requests.

jQuery offers an .ajax() method and various shorthands for accomplishing common tasks using AJAX.
Here’s the jQuery code:

 

$.ajax("google.com") // issue a 'GET' request to fetch google.com's home page
 .done(function(data) { // success handler (status code 200)
 console.log(data);
 })
 .fail(function(xhr) { // error handler (status code not 200)
 console.log("Error occurred: ", xhr.statusText);
});

The first line specifies the URL from which you want to request data. The code then specifies the callback
functions for the success and error conditions (jQuery takes care of checking for readyState and the status code).
Here we have not specify the type of request (GET) or whether it is asynchronous or not.
This is because jQuery uses GET by default and $.ajax() is asynchronous by default.
We can override these parameters (and more) to fine-tune your request:

 

$.ajax({
	url: "www.xyz.com",
	async: true, // false makes it synchronous
	type: "GET", // 'GET' or 'POST' ('GET' is the default)
	done: function(data) { // success handler (status code 200)
		console.log(data);
	},
	fail: function(xhr) { // error handler (status code not 200)
		console.log("Error occurred: ", xhr.statusText);
	}
});

For more info please visit:- http://api.jquery.com/jquery.ajax/

Note:- .done() and .fail() were introduced in jQuery 1.8. If you’re using an older version of jQuery, use .success() and .error(), respectively.

 

Programming is easy…