Ajax with jQuery

Contact Us or call 1-877-932-8228
Ajax with jQuery

Ajax with jQuery

jQuery provides Ajax support that abstracts away painful browser differences. It offers both a full-featured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $.fn.load().

Most jQuery applications don't in fact use XML; instead, they transport data as plain HTML or JSON (JavaScript Object Notation).

In general, Ajax does not work across domains. Exceptions are services that provide JSONP (JSON with Padding) support, which allow limited cross-domain functionality.

Data Types

jQuery generally requires some instruction as to the type of data you expect to get back from an Ajax request; in some cases the data type is specified by the method name, and in other cases it is provided as part of a configuration object. There are several options:

  • text - For transporting simple strings, usually to be placed directly into the page
  • html - For transporting blocks of HTML, usually to be placed directly into the page
  • xml - For transporting blocks of XML, which can be parsed to provide data
  • script - For adding a new script to the page -- this type of request uses a concept called dynamic script tagging instead of XMLHttpRequest, and is therefore not limited by the same origin policy
  • json - For transporting JSON-formatted data, which can include JavaScript strings, arrays, and objects
  • jsonp - A variant of JSON, which can be used to retrieve content from other servers -- this type of request also uses dynamic script tagging

Note: As of jQuery 1.4, if the JSON data sent by your server isn't properly formatted, the request may fail silently. See http://json.org for details on properly formatting JSON, but as a general rule, use built-in language methods for generating JSON on the server to avoid syntax issues.

It is recommended to use the JSON format in most cases, as it provides the most flexibility. It is especially useful when your server environment is PHP, since JSON is also native to that language.

JSON and XML - what do they look like?

JSON:

person = {"age" : 33, "name" : "Joshua"}

XML:

<person>
	<age>33</age>
	<name>Joshua</name>
</person>

A is for Asynchronous

The asynchronicity of Ajax catches many new jQuery users off guard. Because Ajax calls are asynchronous by default, the response is not immediately available. Responses can only be handled using a callback. So, for example, the following code will not work:

var response;
	$.get('foo.php', function(r) { response = r; });
	console.log(response); // undefined!

Instead, we need to pass a callback function to our request; this callback will run when the request succeeds, at which point we can access the data that it returned, if any.

$.get('foo.php', function(response) { console.log(response); });

Same-Origin Policy and JSONP

In general, Ajax requests are limited to the same protocol (http or https), the same port, and the same domain as the page making the request. This limitation does not apply to scripts that are loaded via jQuery's Ajax methods.

The other exception is requests targeted at a JSONP service on another domain. In the case of JSONP, the provider of the service has agreed to respond to your request with a script that can be loaded into the page using a <script> tag, thus avoiding the same-origin limitation; that script will include the data you requested, wrapped in a callback function you provide.

Ajax and Developer Tools

Modern browsers have for several years now shipped with built-in developer tools - tools invaluable for those of us building, testing, and maintaining Ajax-based code. Right-click on any part of a page in Chrome, Firefox, Safari, or Internet Explorer and choose "Inspect Element" to access the Developer Tools; on Safari, check "Show Develop menu in menu bar" in the "Advanced" preferences to enable this feature. The "Network" tab (known as "Timelines" in Safari) gives us a clear view of requests our browser sends and the response we receive, in real time. If something isn't going as expected with an Ajax request, this is the first place to look to track down what's wrong.

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.

Let's look at an example: we'll use jQuery to build a page we looked at previously:

  1. Navigate on the command line to jQuery/Demos.
  2. Type npm install from the command line to install the needed Node.js modules.
  3. Type npm start to start the Node.js server.
  4. Open http://localhost:8080/UsingXMLHttpRequest-Ajax.html in a browser.
  5. Open jQuery/Demos/UsingXMLHttpRequest-Ajax.html in a code editor to review the code.

Code Sample:

jQuery/Demos/UsingXMLHttpRequest-Ajax.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery ajax - XML</title>
<link href="styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#btn').click(function() {
			$.ajax({
				url: "Demo",
				data: {
					FirstName: "Nat",
					LastName: "Dunn"
				},
				dataType: "xml"
			}).done(function(xml) {
				var h1 = $(xml).find("h1");
				$("#Content").html(h1);
			});
			return false;
		});
	});
</script>
</head>
<body>
	<button id="btn">Start</button>
	<div id="Content"></div>
</body>
</html>

We use jQuery's ready method to add a listener on the button; when clicked, we invoke the jQuery ajax method.

We use three parameters in our call to $.ajax

  1. url: "Demo" specifies that the Ajax request is sent to /Demo, a response route we've setup in our Node.js server; since we don't state otherwise, $.ajax uses the default GET method.
  2. data: { FirstName: "Nat", LastName: "Dunn" } sets the parameters included with the request; in this case, we are requesting the URL http://localhost:8080/Demo?FirstName=Nat&LastName=Dunn; that is, we include two GET parameters, FirstName and LastName.
  3. The dataType: "xml" parameter tells jQuery that we are expecting XML as the mime type from the response.

The done callback allows us to handle the response, if any, that we get back from the remote resource. As /Demo responds with a single <h1> tag (<h1>Hello Nat Dunn</h1>), we use jQuery's find method to get the contents of the <h1> tag - that is, "Hello Nat Dunn" - and assign the value to a local variable h1. Lastly, we set the <div> with id Content to that value, using jQuery's html method.

Let's look at another example, where we process a JSON (instead of, as in the last example, XML) response:

Code Sample:

jQuery/Demos/UsingXMLHttpRequest-Ajax-JSON.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery ajax - JSON</title>
<link href="styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#btn').click(function() {
			$.ajax({
				url: "DemoJSON",
				data: {
					FirstName: "Nat",
					LastName: "Dunn"
				},
				dataType: "json"
			}).done(function(data) {
				$("#Content").html('');
				$.each(data, function(index, element) {
					$('#Content').append('<p>' + element.greeting + ', ' + element.name + '!</p>');
				});
			});
			return false;
		});
	});
</script>
</head>
<body>
	<button id="btn">Start</button>
	<div id="Content"></div>
</body>
</html>

Open http://localhost:8080/UsingXMLHttpRequest-Ajax-JSON.html in your browser to view the demo.

We again use jQuery's ready method to add a listener on the button; when clicked, we invoke the jQuery ajax method.

The key difference between this example and the last one is that this ajax call is expecting to receive a JSON response. If we examine the Node.js response route /DemoJSON?FirstName=Nat&LastName=Dunn, we see that the returned data is

[{"greeting":"hello","name":"Nat Dunn"},
{"greeting":"hola","name":"Nat Dunn"},
{"greeting":"bon jour","name":"Nat Dunn"},
{"greeting":"hallo","name":"Nat Dunn"}]

The JSON returned is an array with four elements, where each element is an object with a greeting field ("hello" in various languages) and a name field (the full name corresponding to the first and last names passed as GET parameters.

In UsingXMLHttpRequest-Ajax-JSON.html, we process the JSON response using jQuery's $.each method. We first set the html of #Contents <div> to '', so that subsequent clicks of the button 'wipe clean' any existing content. We then iterate over the four-element JSON array and, for each element, we append a paragraph to the #Contents <div> with the greeting and name.

Next