Lesson 21: Easy AJAX Calls with jQuery

By Maria Antonietta Perna

jQuery provides a rich set of handy methods you can use to Ajaxify your web pages.

Back in lesson 18 you used AJAX by dealing directly with the XMLHttpRequest object. You also performed some feature testing for Internet Explorer browsers that didn't support the XMLHttpRequest object.

jQuery provides wrapper methods that shield you from the inner mechanisms of an AJAX request.

In this lesson, you will learn how to use:

  • $.load() to request content from an HTML page;
  • the shorthand $.get() method;
  • the shorthand $.post() method;
  • the full-blown $.ajax() method.

To follow along with the examples in this lesson, you need to have access to a server, just as you did back in lesson 18.

How do I load HTML content with jQuery AJAX?

jQuery offers a very simple approach to loading HTML content on your web page asynchronously. Just use the $.load() function and you're done.

If you use $.load(htmlPageUrl) passing only the URL of the HTML document as argument, the entire content of the HTML document is loaded into the calling page.

Instead, I like to use $.load(htmlPageUrl fragmentIdentifier), which exactly targets the bit of content I intend to retrieve.

Here's how this is done in practice.

Prepare an HTML page containing a div element with an id of content and a paragraph element with some dummy content. Save it as content.html (or anything you like), and upload it to your server. This document provides the content to retrieve using AJAX.

Prepare a second HTML page containing a link element, a div element with an id of result, a reference to the jQuery library in the <head> section, and enclosing <script> tags in the <body> section for your own jQuery-powered JavaScript code.

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 21: Easy AJAX Calls with jQuery</title>
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
		</head>
		<body>
		<h1>Lesson 21: Easy AJAX Calls with jQuery load()</h1>
		
		<p><a href="#">Click here to fetch HTML content</a></p>
		
		<div id="result">
		
		</div>
		
		<script type="text/javascript">
		
		//JavaScript AJAX code here
		
		</script>
			
		</body>
		</html>
		
		

For these simple demos, we're going to embed our JavaScript code inside the HTML page. However, keep in mind that, if you write code for a website, it's highly recommended that you use external JavaScript files.

When the user clicks on the link on your HTML page, an AJAX request will be made to content.html targeting the text inside the div element with an id of content. This text is dynamically inserted in the div with an id of result in the calling page.

To achieve this, enter the following code snippet inside the enclosing <script> tags:

		
		$(document).ready(function()
		
		{
		
		//Attach a handler to the click event
		
		//of the link on the page:
		
		$('a').click(function()
		
		{
		
		//Target the div with id of result
		
		//and load the content from the specified url
		
		//and the specified div element into it:
		
		$('#result').load('content.html #content');
		
		});
		
		});
		
		

Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.

Click the link, and if all goes well, the dummy text from content.html is loaded inside the div element on the page. The operation takes place asynchronously without a full page refresh.

How do I use $.get()?

As nice and simple as $.load() is, it can't perform all types of content requests. A more flexible approach is offered by the $.get() method.

You can use $.get() to load data from the server with a GET HTTP request - that is, via a query string (see Lesson 10: Passing variables in a URL in the PHP tutorial on HTML.net for a great introduction to query strings).

$.get(url, {dataKey1 : 'dataValue1', dataKey2 : 'dataValue2'}, optionalSuccessFunction) takes in 3 arguments:

  1. theURL where the data you want to retrieve is stored;
  2. optionally, some data, if you want to send data to the server with the request. This is done using either a string or what is called object literal or map, that is, comma-separated key:value pairs inside curly braces. For instance: {'First Name' : 'John', 'Last Name' : 'Smith'} sends the First Name and Last Name values to the server together with the AJAX GET request;
  3. and a function that deals with the returned data if you want to display or process the successful response in any way.

Let's see how to use jQuery .get() to retrieve the XML document you used back in lesson 18.

The HTML page that makes the AJAX request remains unchanged from the previous example. Rewrite the JavaScript code as follows:

		
		$(document).ready(function()
		
		{
		
		//Store the URL value in a variable
		
		var url = "content.xml";
		
		
		/*************************************/
		
		
		//Package the result-handling code
		
		//in its own function: it's more readable
		
		function processData(data)
		
		{
		
		//This variable will hold the result
		
		//converted into a string for display
		
		var resultStr = "";
		
		//use jQuery .find() to extract the language
		
		//element from the returned data
		
		//and store it in an array
		
		var items = $(data).find('language');
		
		//loop over each language item with
		
		//jQuery .each() function
		
		$(items).each(function(i)
		
		{
		
		//extract the text of each language item and
		
		//add it to the resultStr variable with a line break.
		
		//Notice the use of $(this)
		
		//to refer to the item currently being
		
		//inspected by the loop
		
		resultStr += $(this).text() + '<br />';
		
		//add the final string result to div element
		
		//with the id of result using .html()
		
		$('#result').html(resultStr);
		
		});
		
		}
		
		
		/****************************************/
		
		
		//Attach a click handler to the link element:
		
		//when the user clicks on the link, the AJAX
		
		//request is sent to the server:
		
		$('a').click(function()
		
		{
		
		//use $.get() passing the url variable and
		
		//the name of the result-handling function
		
		//as arguments:
		
		$.get(url, processData);
		
		});
		
		});
		
		

Save all your files on the server and click on the link. If all goes well, you should see a list of programming languages being displayed on the page without a full page refresh.

In the example above, you came across jQuery .find() and jQuery .each().

$.find() is used to find a DOM element's descendants or children. In the example above, you used it to find all children called language of the root XML element contained in the variable called data. Further details on $.find() can be accessed on http://api.jquery.com/find/.

$.each(index) is a for ... loop done the jQuery way. It's extremely concise and efficient. Notice the use of $(this) inside the $.each() function block. This is a snappy way of referring to the item the loop is currently processing: in our example above $(this) refers to one of the language items in the items array.

More details on $.each() can be found on http://api.jquery.com/each/.

How do I use $.post()?

If you want to use POST instead of GET in your AJAX calls, you can use $.post().

Unlike GET requests, POST requests don't use a query string to send data. If you intend to send more than a few bits of data to the sever, or if you intend to send sensitive data, it's recommended you use an HTTP POST request.

The way you implement $.post() is very similar to the way you implemented $.get() in the previous example. I invite you to experiment with it on your own and to visit http://api.jquery.com/jQuery.post/ for more code samples and useful details.

How do I use $.ajax()?

If you need greater flexibility, the full-blown $.ajax() function offers a great number of settings.

For instance, let's say you want to retrieve a list of programming languages from the XML document you used in the previous example. You might want to specify the following options:

  1. the request must be an HTTP GET;
  2. the page from which the result is returned must not be in the browser's cache;
  3. the response returned by the server is of data-type XML;
  4. the request is made in html;
  5. there must be a function that handles the returned result if all goes well;
  6. and, finally, there must be a function that handles errors in case the request is not successful.

Use the HTML page and the XML document from the previous example. Also, keep the url variable and the processData() function from the previous exercise - you will use both as the url and the success arguments respectively inside the $.ajax() function. Delete everything else inside the document.ready() function. Just below the processData() function, write the following code:

		
		//Package the code that handles
		
		//error message in case the request
		
		//is not successful:
		
		function errorAlert(e, jqxhr)
		
		{
		
		alert("Your request was not successful: " + jqxhr);
		
		}
		
		
		/*************************************/
		
		
		//Attach a click handler to the
		
		//link element on the page
		
		$('a').click(function()
		
		{
		
		//Prepare the AJAX request that
		
		//will be sent when the user clicks the link:
		
		$.ajax(
		
		{
		
		type: "GET",
		
		cache: false,
		
		url: url,
		
		dataType: "xml",
		
		contentType: "text/html",
		
		success: processData,
		
		error: errorAlert
		
		}); //end of $.ajax
		
		}); //end of click handler
		
		});  //end of $.ready function
		
		

Save your work and preview it in a browser. The result should be similar to the previous example. If an error occurs, you'll be presented with an alert box. The errorAlert() function has an e argument that represents the type of error, and an jqxhr argument that represents the request as a jQuery object.

In case an error occurs, details about the error are automatically contained in the arguments provided and will be displayed in the alert box.

Do you want to test the error catching function? Simply replace dataType: "xml" in the $.ajax() function with dataType: "text/xml". Save all your files and run the HTML page. Now, when you click the link, an alert box should pop up displaying a parser error message.

More on $.ajax() can be found on http://api.jquery.com/jQuery.ajax/.

Summary

You got to the end of the lesson, and also to the end of this JavaScript tutorial. Congratulations!

Now you're familiar with the core JavaScript syntax and objects. You know how to include the jQuery library in your projects to add flair to your web pages and make AJAX calls easily and efficiently.

I encourage you to keep experimenting with code samples and to be an active participant in JavaScript forums. Why not starting from the forums on HTML.net? It's easy to register and meet with the real experts in your programming language of choice.

As you might have already guessed, the best way to learn coding is to keep coding ... a lot.

The only thing left is for me to wish you hours of fun with your new friends, JavaScript and jQuery.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 20: Cool Animation Effects with jQuery

>>