Easy Ajax with jQuery

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

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • http://www.ajaxandjquery.com Tommy Callaway

    Great info! I’m all about learning AJAX. I just started a blog, http://www.ajaxandjquery.com on the same thing. I’ll also be posting lots of tutorials. Thanks for the great post!

  • http://www.findferry.co.uk Ferry

    Thanks for great info, trying to get the hang of AJAX. Nice website, keep up the good work :-)

  • http://www.rmgstock.com zillur

    load(“script.php”)

    can i use the it like this..

    load(“script.php?id=”);

  • http://www.1click.co.za TimNape

    Thought Jquery was too much to learn and ws doing traditional ajax.
    Thx man

  • http://www.infyways.com/ Mark William

    Thank you so much for such a nice article.
    I liked it very much.
    Thank you for sharing.

  • http://way2learning.net/ webhost

    Thanks dude.. you made my work easy….

  • Jordie Littell

    Does the trigger for the AJAX request have to be a button. Could we include the generate id in a div element and use that to send the ajax request?