jQuery's Ajax-Related Methods

Contact Us or call 1-877-932-8228
jQuery's Ajax-Related Methods

jQuery's Ajax-Related Methods

While jQuery does offer many Ajax-related convenience methods, the core $.ajax method is at the heart of all of them, and understanding it is imperative. We'll review it first, and then touch briefly on the convenience methods.

The $.ajax method offers features that the convenience methods do not. Once you have gained some experience with Ajax in jQuery, it is easiest to just use this one method.

$.ajax

jQuery's core $.ajax method is a powerful and straightforward way of creating Ajax requests. It takes a configuration object that contains all the instructions jQuery requires to complete the request. The $.ajax method is particularly valuable because it offers the ability to specify both success and failure callbacks. Also, its ability to take a configuration object that can be defined separately makes it easier to write reusable code.

$.ajax(options)
$.ajax(url, options)

Options for $.ajax

There are many, many options for the $.ajax method, which is part of its power. For a complete list of options, visit http://api.jquery.com/jQuery.ajax/.

Note that the url can either be provided as a separate parameter or as part of the options object.

Here are some of the more commonly used options:

  • url - The URL for the request. Required either as an option or as a separate parameter.
  • type - The type of the request, "POST" or "GET". Defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all browsers.
  • async - Set to false if the request should be sent synchronously. Defaults to true. Note that if you set this option to false, your request will block execution of other code until the response is received.
  • cache - Whether to use a cached response if available. Defaults to true for all data types except script and jsonp. When set to false, the URL will simply have a cachebusting parameter appended to it.
  • success - A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object.
  • error - A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.
  • complete - A callback function to run when the request is complete, regardless of success or failure. The function receives the raw request object and the text status of the request. This function will run after any error or success function, if those are also specified.
  • context - The scope in which the callback function(s) should run (i.e. what this will mean inside the callback function(s)). By default, this inside the callback function(s) refers to the object originally passed to $.ajax.
  • data - The data to be sent to the server. This can either be an object, like { foo:'bar',baz:'bim' } , or a query string, such as foo=bar&baz=bim.
  • dataType - The type of data you expect back from the server. By default, jQuery will look at the MIME-type (from the Content-Type header) of the response if no data type is specified.
  • jsonp - The callback parameter name to send in a query string when making a JSONP request. Defaults to callback. (jQuery will add a parameter callback=XXXXXX to the query string; this option sets the parameter name, and the following option sets the parameter value).
  • jsonpCallback - The value of the callback parameter to send in a query string when making a JSONP request. Defaults to an auto-generated random value.
  • timeout - The time in milliseconds to wait before considering the request a failure.

The url option is the only required property of the $.ajax configuration object; all other properties are optional.

Using the Core $.ajax Method

$.ajax({
	// the URL for the request
	url : 'post.php',

	// the data to send
	// (will be converted to a query string)
	data : { id : 123 },

	// whether this is a POST or GET request
	type : 'GET',

	// the type of data we expect back
	dataType : 'json',

	// code to run if the request succeeds;
	// the response is passed to the function
	success : function(json) {
		$('<h1/>').text(json.title).appendTo('body');
		$('<div class="content"/>')
			.html(json.html).appendTo('body');
	},

	// code to run if the request fails;
	// the raw request and status codes are
	// passed to the function
	error : function(xhr, status) {
		alert('Sorry, there was a problem!');
	},

	// code to run regardless of success or failure
	complete : function(xhr, status) {
		alert('The request is complete!');
	}
});

Note: A note about the dataType setting: if the server sends back data that is in a different format than you specify, your code may fail, and the reason will not always be clear, because the HTTP response code will not show an error. When working with Ajax requests, make sure your server is sending back the data type you're asking for, and verify that the Content-Type header is accurate for the data type. For example, for JSON data, the content type should be application/json.

Convenience Methods

If you don't need the extensive configurability of $.ajax, and you don't care about handling errors, the Ajax convenience functions provided by jQuery can be useful, terse ways to accomplish Ajax requests. These methods are just "wrappers" around the core $.ajax method, and simply pre-set some of the options on the $.ajax method.

The convenience methods provided by jQuery are:

  • $.get - Perform a GET request to the provided URL.
  • $.post - Perform a POST request to the provided URL.
  • $.getScript - Add a script to the page.
  • $.getJSON - Perform a GET request, and expect JSON to be returned.

In each case, the methods take the following arguments, in order:

  • url - The URL for the request. Required.
  • data - The data to be sent to the server. Optional. This can either be an object or a query string, such as foo=bar&baz=bim.
    • Note: This option is not valid for $.getScript.
    • Also, this parameter is truly optional - if you do not want to supply it, you don't have to supply a placeholder value (jQuery looks at the type of the second parameter to determine if it is your parameters; if the second parameter is a function, it uses it as the success callback described below)
  • success - A callback function to run if the request succeeds. Optional. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object.
  • dataType - The type of data you expect back from the server. Optional. (Note: This option is only applicable for methods that don't already specify the data type in their name.)

Using jQuery's Ajax Convenience Methods

// get plain text or html
$.get('/users.php', { userId : 1234 }, function(resp) {
	console.log(resp);
});

// add a script to the page, then run a function defined in it
$.getScript('/js/myScript.js', function() {
	functionFromMyScript();
});

// get JSON-formatted data from the server
// resp will be a single object parsed from the incoming JSON
$.getJSON('/details.php', function(resp) {
	$.each(resp, function(k, v) {
		console.log(k + ' : ' + v);
	});
});

$.fn.load

The $.fn.load method is unique among jQuery's Ajax methods in that it is called on a selection. The $.fn.load method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s). In addition to providing a URL to the method, you can optionally provide a selector as part of the URL parameter; jQuery will fetch only the matching content from the returned HTML.

Using $.fn.load to Populate an Element

$('#newContent').load('/foo.html');

Using $.fn.load to Populate an Element Based on a Selector

$('#newContent').load('/foo.html #myDiv h1:first', function(html) {
	alert('Content updated!');
});

Ajax Examples

Code Sample:

jqy-ajax/Demos/ajax-text.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Testing Ajax with HTML</title>
<script src="../../jqy-libs/jquery.js"></script> 
<script>
$(document).ready(function() {
	$.ajax("data/blurb.html", {
			type: "get",
			dataType: "html",
			success: function(data) {
				$('#results1').html(data);
			},
			error: function(xhr, status, err) {
				$('#results1').html("Error " + status + ", " + err);
			}
		} );
	$('#results2').load("data/blurb.html");
});
</script>
</head>
<body>
<h1>Here is the Ajax we received via $.ajax:</h1>
<div id="results1"></div>
<h1>Here is the Ajax we received via $.load:</h1>
<div id="results2"></div>
</body>
</html>

We load the HTML text two ways, using $.ajax and $.fn.load.

Using $.ajax, we supply an options object specifying the GET method, HTML data, and both success and error functions. You can test the error capability by changing the URL to a non-existent file name.

The $.fn.load approach is simpler -- we identify the receiving element, and simply load the file.

Code Sample:

jqy-ajax/Demos/ajax-json.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Testing Ajax with JSON</title>
<script src="../../jqy-libs/jquery.js"></script> 
<script>
$(document).ready(function() {
	$.ajax("data/people.json", {
		type: "get",
		dataType: "json",
		success: function(data) {
			var $list = $('<ol/>').appendTo('#results');
			$.each(data, function() {
				$list.append(
						'<li>' + this.firstName + ' ' + this.lastName + '</li>');
			});
		},
		error: function(xhr, status, err) {
			$('#results').html("Error " + status + ", " + err);
		}
	} );
});
</script>
</head>
<body>
<h1>Here are the contents of our JSON data:</h1>
<div id="results"></div>
</body>
</html>

This example is similar to the previous one, but we can't use $.fn.load for JSON data.

This time we supply an options object specifying the GET method, JSON data, and again both success and error functions.

We based our treatment of the JSON data upon our knowledge that it is an array of objects, each with two fields: firstName and lastName.

You can test the JSON-related aspects of the error capability by munging the data file.

Next