Easy Ajax with jQuery

Share this article

This article was written in 2011 and remains one of our most popular posts. If you’re keen to learn more about jQuery, you may find this recent article on jQuery 1.9 of great interest.
Ajax is changing web applications, giving them a responsiveness that’s unheard of beyond the desktop. But behind all the hype, there’s not much to Ajax — HTML, JavaScript, and XML are nothing new, and in this tutorial, I’ll show you how to simplify the process of adding Ajax to your application even further with the help of jQuery.

What’s Ajax?

You’ve probably heard about Ajax before, or at least used an Ajax-based application — Gmail, for instance. Quite simply, Ajax is a technique for handling external data through JavaScript asynchronously, without reloading the entire page. SitePoint offers a good introduction to Ajax. Jesse James Garrett is credited with coining the term in this article. Unfortunately, in-depth tutorials on practical ways to enter the world of Ajax are few and far between. To add to the problem, the XMLHttpRequest class used by Ajax isn’t very easy for beginning web developers to use. Luckily, a number of JavaScript libraries offer an easier way. Today I’ll show you how jQuery — one of these libraries — allows you to easily add Ajax to your application.

What’s jQuery?

jQuery is another mature JavaScript library that offers some features that the others do not. Admittedly, it’s not exactly as lightweight as some of the other offerings: jQuery comes in at 19kb, while moo.fx is only 3kb. You can read more about jQuery at The JavaScript Library World Cup for a comparison of a few other JavaScript libraries that offer similar functionality.

Assumed Knowledge

To complete this tutorial, you’ll need some basic JavaScript knowledge. If you know any C-style languages, you’ll get the hang of JavaScript in no time. Just think curly braces, function declarations, and optional semicolons at the end of each line (they’re not optional with jQuery, though). If you’re keen to get started with JavaScript, see this excellent, concise JavaScript tutorial designed for programmers. Also, since we’re talking about web applications, a basic knowledge of HTML is required.

jQuery 101

Let’s walk through a quick introduction to jQuery. To be able to use it in your pages, you’ll first need to download the library. You can download the latest version — 1.8 at the time of writing. jQuery’s methodology is simple: find things, do stuff. We select elements from the document (via the DOM) using the jQuery function, aliased as $(). This handy function acts just like document.getElementById(), except that instead of only supporting IDs, it supports CSS selectors and some XPath selectors; and, instead of returning one element, it can return an array of elements. Okay, so maybe a better description of $() is that it’s like document.getElementById() on steroids. We then use functions to perform actions on our selections. For example, to append the text “Hello World!” to all divs with the class 'foo', then set the color to red, we’d use the following code:
$("div.foo").append("Hello World!").css("color","red");
Easy! Normally, this task would require two lines of code, like so:
$("div.foo").append("Hello World!"); 
$("div.foo").css("color","red");
//
jQuery’s chainable methods allow us to write much more compact code than other JavaScript libraries. There are functions in jQuery that don’t need an object, as they work independently, and many of the Ajax functions fall into this group. For example, the post function, which we will soon make use of, is called by typing $.post(parameters). For more jQuery functions, check the online documentation or visualjquery.com.

Example 1 – Our First Ajax Application

As an example, we’re going to make an interactive concept generator. Basically, this involves our selecting two terms at random from a list, then combining them to create a phrase. For this exercise, we’ll use web 2.0 buzzwords (‘Mashup’, ‘Folksonomy’, ‘Media’ and so on), and normally we’d fetch these terms from a flat file. To save you from downloading every single combination (or at least every element) in JavaScript, we’re going to generate it on the fly at the server end, and fetch it for the client with jQuery. jQuery integrates perfectly with normal JavaScript, so you’ll find it an easy task to work it into your code. Server-side Code (PHP) To keep it simple, we’ll use the basic code below to create our concept generator. Don’t worry about how it works, just look at what it does: it outputs a randomized quote. Note that this code doesn’t output XML — it merely outputs raw text:
<?php 
header("Cache-Control: no-cache"); 
// Ideally, you'd put these in a text file or a database.  
// Put an entry on each line of 'a.txt' and use $prefixes = file("a.txt"); 
// You can do the same with a separate file for $suffixes. 
$prefixes = array('Mashup','2.0','Tagging','Folksonomy'); 
$suffixes = array('Web','Push','Media','GUI'); 
// This selects a random element of each array on the fly 
echo $prefixes[rand(0,count($prefixes)-1)] . " is the new "  
   . $suffixes[rand(0,count($prefixes)-1)]; 
// Example output: Tagging is the new Media 
?>
Here, I’ve used the Cache-Control header response because Internet Explorer has a habit of caching pages that have the same URL, even if the content between the pages differs. Obviously, that defeats the purpose of our script — the production of a new quote on every load. We could have used jQuery to include a random number in the URL that would then be discarded, but it’s easier to address this caching issue on the server side than the client side. Client-side Code (HTML) Let’s start creating the HTML for the front end, then work our Ajax into it. All we need on the page is a button that users can click to request another quote, and a div into which we’ll put the quote once we’ve received it from the server. We’ll use jQuery to select this div and load the quote into it, and we’ll reference the div by its id. If we wanted to, we could use jQuery to load the quote into multiple elements, with the help of a class, but an id is all we need for now. Let’s make this the content of our body element:
<input type="submit" id="generate" value="Generate!"> 
<div id="quote"></div>
We can put the quote itself inside the div. Normally, we’d have a lengthy onSubmit event for the button (the input with the id 'generate'). Sometimes, we’d have an onSubmit event handler that called a JavaScript function. But with jQuery, we don’t even need to touch the HTML — we can separate behavior (the event handler) from the structure (the page HTML) with ease. Client-side Code (jQuery) It’s time to bring our back end together with our front end using jQuery. I mentioned earlier that we can select elements from the DOM with jQuery. First, we have to select the button and assign an onClick event handler to it. Within the code for this event, we can select the div and load the content of our script into it. Here’s the syntax for the click event handler:
$("element expression").click(function(){ 
  // Code goes here 
});
As you probably already know, if we were to select this element in CSS, the # would identify that we were making our selection using the element’s id attribute. You can use exactly the same syntax with jQuery. Therefore, to select the button with the id 'generate'
(which we gave it above), we can use the element expression #generate. Also, be aware that this syntax defines our event handler as an anonymous function within the event itself. Mark Wubben’s JavaScript Terminology page offers a great explanation of anonymous functions, if you’d like to know more. We’re going to use one of jQuery’s higher level Ajax functions, load(). Let’s assume that our generator script is saved as script.php. Let’s integrate it with our client side with the help of the load() function:
$("#generate").click(function(){ 
  $("#quote").load("script.php"); 
});
That’s it: three lines of code, and we have fully functioning Ajax random quote generator! Well, almost. The problem with JavaScript is that code that’s not within a function is executed as soon as the browser reaches it during rendering — not once the page has finished rendering. As such, this code will try to attach to an element that has not yet loaded. Normally, we’d use window.onload to deal with this issue. However, the limitation with that approach is that window.onload is called once everything has finished loading — images and all. We’re not interested in waiting for those images — it’s just the DOM that we want access to. Fortunately, jQuery has $(document).ready(), which, as its name suggests, is executed when the DOM is ready to be manipulated. The Complete Code Here’s the complete code, including the $(document).ready wrapper and some basic HTML and CSS:
<html> 
<head> 
  <title>Ajax with jQuery Example</title> 
  <script type="text/JavaScript" src="jquery.js"></script> 
  <script type="text/JavaScript"> 
  $(document).ready(function(){ 
    $("#generate").click(function(){ 
      $("#quote p").load("script.php"); 
    }); 
  }); 
  </script> 
<style type="text/css"> 
    #wrapper { 
      width: 240px; 
      height: 80px; 
      margin: auto; 
      padding: 10px; 
      margin-top: 10px; 
      border: 1px solid black; 
      text-align: center; 
    } 
  </style> 
</head> 
<body> 
  <div id="wrapper"> 
    <div id="quote"><p> </p></div> 
    <input type="submit" id="generate" value="Generate!"> 
  </div> 
</body> 
</html>
This code is also included in this downloadable zip file. Remember, this code assumes the jQuery library has been saved as jquery.js in the same folder as the PHP script and the HTML front end. Now that you’re familiar with jQuery, let’s move on to something more complicated: form elements and XML handling. This is true Ajax!
Go to page: 1 | 2 | 3

Frequently Asked Questions (FAQs) about AJAX and jQuery

What is the difference between AJAX and jQuery?

AJAX, which stands for Asynchronous JavaScript and XML, is a set of web development techniques used to create asynchronous web applications. It allows you to send and retrieve data from a server without interfering with the display and behavior of the existing page. On the other hand, jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers.

How can I use AJAX with jQuery?

jQuery provides several methods for AJAX functionality. The $.ajax() method is the most flexible, but also the most complicated. For simpler requests, jQuery provides helper methods like $.get(), $.post(), and $.load(). These methods return a jqXHR object, which is a superset of the browser’s native XMLHttpRequest object. This object can be used to handle callbacks.

What is the role of JSON in AJAX?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. In AJAX, JSON is often used as the data format for sending data from the server to the client and vice versa. It’s a more efficient and convenient alternative to XML.

How can I handle errors in AJAX?

jQuery’s AJAX methods provide several ways to handle errors. The simplest way is to provide an error callback function as an option to the $.ajax() method. This function will be called if the AJAX request fails for any reason.

Can I use AJAX without jQuery?

Yes, AJAX can be used without jQuery. However, jQuery simplifies the process and takes care of many cross-browser compatibility issues. If you choose to use AJAX without jQuery, you’ll need to use the browser’s native XMLHttpRequest object.

How can I use AJAX to update a part of my web page?

You can use the $.load() method to load data from the server and place the returned HTML into the matched element. This is a simple way to update a part of your web page without refreshing the entire page.

What is the difference between synchronous and asynchronous AJAX requests?

Synchronous AJAX requests block the execution of code until the request has been completed. This means that the browser is unresponsive until the response is received. Asynchronous AJAX requests, on the other hand, allow the execution of code to continue while the request is being processed. This means that the browser remains responsive.

How can I send data to the server using AJAX?

You can send data to the server using the data option of the $.ajax() method. The data can be in the form of a query string, a JavaScript object, or a FormData object.

Can I use AJAX with other JavaScript libraries?

Yes, AJAX can be used with other JavaScript libraries. However, jQuery provides a simple and convenient API for AJAX functionality, which is why it’s often used in conjunction with AJAX.

How can I cancel an AJAX request?

You can cancel an AJAX request by calling the abort() method on the jqXHR object returned by the $.ajax() method. This will immediately terminate the request and trigger the error callback function.

Akash MehtaAkash Mehta
View Author

Akash Mehta is a web developer and freelance writer specializing in web application development.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week