Chapter 1. Using Ajax: Web Apps for a New Generation

image with no caption

Tired of waiting around for your page to reload?

Frustrated by clunky web application interfaces? It’s time to give your web apps that slick, responsive desktop feel. And how do you do that? With Ajax, your ticket to building Internet applications that are more interactive, more responsive, and easier to use. So skip your nap; it’s time to put some polish on your web apps. It’s time to get rid of unnecessary and slow full-page refreshes forever.

Web pages: the old-fashioned approach

With traditional web pages and applications, every time a user clicks on something, the browser sends a request to the server, and the server responds with a whole new page. Even if your user’s web browser is smart about caching things like images and cascading style sheets, that’s a lot of traffic going back and forth between their browser and your server... and a lot of time that the user sits around waiting for full page refreshes.

image with no caption

Web pages reinvented

Using Ajax, your pages and applications only ask the server for what they really need—just the parts of a page that need to change, and just the parts that the server has to provide. That means less traffic, smaller updates, and less time sitting around waiting for page refreshes.

With Ajax, the browser only sends and receives the parts of a page that need to change.

image with no caption

Sometimes the browser doesn’t have to talk to the server at all.

image with no caption
image with no caption

Ajax is a new way of using existing technologies.

Ajax isn’t a whole new technology that you have to learn, like CSS or JavaScript, or a set of graphics techniques you’ll need to crack open PhotoShop to accomplish. Ajax is just a new way of thinking about how to do what you’re already doing, using technologies you probably already know.

image with no caption

So what makes a page “Ajax”?

Ajax is a way of designing and building web pages that are as interactive and responsive as desktop applications. So what does that mean for you? You handle things at the client’s browser whenever you can. Your pages make asynchronous requests that allow the user to keep working instead of waiting for a response. You only update the things on your pages that actually change. And best of all, an Ajax page is built using standard Internet technologies, things you probably already know how to use, like:

  • XHTML

  • Cascading Style Sheets

  • JavaScript

An asynchronous request is a request that occurs behind the scenes.

Ajax applications also use a few things that have been around for a while but may be new to you, like:

  • The XmlHttpRequest

    Note

    We’ll look at all of these in detail before we’re through.

  • XML & JSON

  • The DOM

Your users can keep working while the request is taking place.

Rob’s Rock ‘n’ Roll Memorabilia

Meet Rob. He’s put all his savings into an online rock n’ roll memorabilia store. The site looks great, but he’s still been getting tons of complaints. Customers are clicking on the thumbnail images on the inventory page, but the customers’ browsers are taking forever before they show information about the selected item. Some of Rob’s users are hanging around, but most have just stopped coming to Rob’s online shop altogether.

image with no caption

Ajax pages only talk to the server when they have to... and only about what the server knows.

image with no caption

The problem with Rob’s site isn’t that his server is too slow, but that his pages are sending requests to the server all the time... even when they don’t need to.

Brain Barbell

Not all pages will reap every benefit of Ajax. In fact, some pages wouldn’t benefit from Ajax at all. Which of the benefits that you checked off above do you think Rob’s page will see?

image with no caption

Ajax and rock ‘n’ roll in 5 steps

Let’s use Ajax to fix up Rob’s online store, and get his impatient customers back. We’ll need to make some changes to the existing XHTML page, code some JavaScript, and then reference the script in our XHTML. When we’re done, the page won’t need to reload at all, and only the things that need to change will get updated when users click on the thumbnail images.

Here’s what we’re going to do:

  1. Modify the XHTML web page

    We need to include the JavaScript file we’re going to write and add some divs and ids, so our JavaScript can find and work with different parts of the web page.

    image with no caption
  2. Write a function to initialize the page

    When the inventory page first loads, we’ll need to run some JavaScript to set up the images, get a request object ready, and make sure the page is ready to use.

    image with no caption
  3. Write a function to create a request object

    We need a way to talk to the server and get details about each piece of memorabilia in Rob’s inventory. We’ll write a function to create a request object to let our code talk to the server; let’s call it createRequest(). We can use that function whenever a thumbnail is clicked to get a new request started.

    image with no caption
  4. Get an item’s details from the server

    We’ll send a request to Rob’s server in getDetails(), telling the browser what to do when the server responds.

    image with no caption
  5. Display the item’s details

    We can change the image to display in getDetails(). Then, we need another function, displayDetails(), to update the item’s description when the server responds to our requests.

    image with no caption

Step 1: Modify the XHTML

Let’s start with the easy part, the XHTML and CSS that create the page. Here’s Rob’s current version of the inventory page with a few additions we’ll need:

image with no caption

Run it!

It’s time to get the samples and get going.

Download the examples for the book at www.headfirstlabs.com, and find the chapter01 folder. Now open the inventory.html file in a text editor, and make the changes shown above.

image with no caption

Step 2: Initialize the JavaScript

We need to create the thumbnails.js file, and add a JavaScript function to set up the initial event handlers for each thumbnail image in the inventory. Let’s call that function initPage(), and set it to run as soon as the user’s window loads the inventory page.

To Do

Modify the XHTML

Initialize the page

Create a request object

Get the item’s details

Display the details

image with no caption

To set up the onclick behavior for the thumbnails, the initPage() function has to do two things

  1. Find the thumbnails on the page

    The thumbnails are contained in a div called “thumbnailPane,” so we can find that div, and then find each image within it.

  2. Build the onclick event handler for each thumbnail

    Each item’s full-size image is named with the title of the thumbnail image plus “-detail”. For example, the detail image for the thumbnail with the title FenderGuitar is FenderGuitar-detail.png. That lets us work out the name of the image in our JavaScript.

    The event handler for each thumbnail should set the src tag for the detail image (the one with an id of “itemDetail”) to the detail image (for example, FenderGuitar-detail.png). Once you’ve done that, the browser will automatically display the new image using the name you supplied.

Step 3: Create a request object

When users click on an item’s image, we also need to send a request to the server asking for that item’s detailed information. But before we can send a request, we need to create the request object.

The bad news is that this is a bit tricky because different browsers create request objects in different ways. The good news is that we can create a function that handles all the browser-specific bits.

To Do

Modify the XHTML

Initialize the page

Create a request object

Get the item’s details

Display the details

Go ahead and create a new function in thumbnails.js called createRequest(), and add this code:

image with no caption
image with no caption
image with no caption

Step 4: Get the item’s details

Once a user clicks on an item in the inventory, we need to send a request to the server and ask for the description and details for that item. We’ve got a request object, so here is where we can use that.

To Do

Modify the XHTML

Initialize the page

Create a request object

Get the item’s details

Display the details

And it turns out that no matter what data you need from the server, the basic process for making an Ajax request always follows the same pattern:

  1. Get a request object

    We’ve already done the work here. We just need to call createRequest() to get an instance of the request object and assign it to a variable.

    image with no caption
  2. Configure the request object’s properties

    The request object has several properties you’ll need to set. You can tell it what URL to connect to, whether to use GET or POST, and a lot more... you need to set this all up before you make your request to the server.

    image with no caption
  3. Tell the request object what to do when the server responds

    So what happens when the server responds? The browser looks at another property of the request object, called onreadystatechange. This lets us assign a callback function that should run when the server responds to our request.

    image with no caption
  4. Make the request

    Now we’re ready to send the request off to the server and get a response.

    image with no caption

Brain Power

Why do you think the callback function is assigned to a property called onreadystatechange? What do you think that property name means?

Let’s write the code for requesting an item’s details

Once we know what our function needs to do, it’s pretty easy to write the code. Here’s how the steps map to actual JavaScript in thumbnails.js:

image with no caption

Run it!

Add the getDetails() function to your version of thumbnails.js

Always make sure you have a request object before working with it

The first thing getDetails() does is call createRequest() to get a request object. But you’ve still got to make sure that object was actually created, even though the details of that creation are abstracted away in the createRequest() function:

image with no caption

And here’s how that looks in our code...

image with no caption

The request object is just an object

A request object is just a “normal” JavaScript object, and that means you can set properties on it and call methods. We can talk to the server by putting information in the request object.

To Do

Modify the XHTML

Initialize the page

Create a request object

Get the item’s details

Display the details

We’re still working on getting the details for an item.

image with no caption

Let’s break open() down a bit...

image with no caption

Hey, server... will you call me back at displayDetails(), please?

The properties of the request object tell the server what to do when it receives the request. One of the most important is the onreadystatechange property, which we’re setting to the name of a function. This function, referred to as a callback, tells the browser what code to call when the server sends back information.

image with no caption
image with no caption

Use send() to send your request

All that’s left to do is actually send the request, and that’s easy... just use the send() method on the request object.

image with no caption
image with no caption

You can send data in your URL string.

The request object allows us to send all kinds of data in a variety of ways. In getDetails(), the item name is part of the URL string:

var url= "getDetails.php?ImageID=" +
  escape(itemName);

Since that’s part of the URL sent to the server, we don’t need to send anything else to the server in the send() method. Instead, we just pass null... which means “nothing.”

Asynchronous apps make requests using a JavaScript object, not a form submit.

image with no caption

The server-side code is... ...on the server.

That sounds obvious, but lots of times, you don’t have to (or even get to) write the code your web application is talking to. Instead, you work with an existing program, where you know the inputs and outputs, or tell another group what you need.

Not only that, but you might also have one server-side program that’s written in PHP, and another in ASP.NET... and other than the URL, you don’t have to change your JavaScript code at all. Take a look:

image with no caption

The server usually returns data to Ajax requests

In a traditional web app, the server always responds to a request from the browser by sending back a new page. The browser throws away anything that’s already displayed (including any fields the user has filled in) when that new page arrives.

Traditional server-side interactions

image with no caption

Ajax server-side interactions

In an Ajax app, the server can return a whole page, part of a page, or just some information that will be formatted and displayed on a web page. The browser only does what your JavaScript tells it to do.

image with no caption

Ajax is server-agnostic

Ajax doesn’t require any particular server technology. You can use Active Server Pages (ASP), PHP, or whatever you need and have access to. In fact, there’s no need to get into the details of the server-side technology because it doesn’t change how you build your Ajax apps.

Here’s all that Ajax really sees:

image with no caption

Brain Power

What happens? What’s wrong with the page? What do you need to do to fix the problem?

Use a callback function to work with data the server returns

How do we show the textual description for each item? Let’s assume the server will send the details about an item as pre-formatted text in the responseText property of the request object. So we just need to get that data and display it.

To Do

Modify the XHTML

Initialize the page

Create a request object

Get the item’s details

Display the details

Our callback function, displayDetails(), needs to find the XHTML element that will contain the detail information, and then set its innerHTML property to the value returned by the server.

image with no caption

Get the server’s response from the request object’s responseText property

The data we want is in the request object. Now we just need to get that data and use it. Here’s what we need:

image with no caption

Relax

Confused about getting your server-side program working?

Flip to Appendix A for some help on getting things working on the server. There are also some helpful server-side resources for the book online at http://www.headfirstlabs.com.

Goodbye traditional web apps...

Rob’s page is working more smoothly now, customers are coming back in droves, and you’ve helped pair vintage leather with the next-generation web.

Rob’s old, traditional web app:

  • ...reloaded the entire page when a user clicked on an item’s thumbnail image.

  • ...took a long time to load because the entire page had to be rendered by the browser on every click.

    Note

    These aren’t problems that just Rob’s having. Almost all traditional web apps have these problems in some form or fashion.

  • ...felt unresponsive because the user had to wait on all those page refreshes.

  • ...lost Rob business, annoyed his customers, and drained his bank account.

Rob’s new, Ajax app:

  • ...only changed the part of the page that needed to be updated.

    Note

    Compare these benefits with the list in Sharpen your pencil Solution... they should look pretty similar.

  • ...lets users keep viewing the page while images and descriptions are loaded behind the scenes, asynchronously.

  • ...reduced the need for his users to have super-fast connections to use his site.

image with no caption

Get Head First Ajax now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.