Member Sign In
Not a member?

A Wired.com user account lets you create, edit and comment on Webmonkey articles. You will also be able to contribute to the Wired How-To Wiki and comment on news stories at Wired.com.


It's fast and free.

Webmonkey is a property of Wired Digital.
processing...
Join Webmonkey

Please send me occasional e-mail updates about new features and special offers from Wired/Webmonkey.
Yes No

Please send occasional e-mail offers from Wired/Webmonkey affiliated web sites and publications, and carefully selected companies.
Yes No

I understand and agree that registration on or use of this site constitutes agreement to Webmonkey's User Agreement and Privacy Policy.
Webmonkey is a property of Wired Digital.
processing...

Retrieve Sign In

Please enter your e-mail address or username below. Your username and password will be sent to the e-mail address you provided us.

or
Webmonkey is a property of Wired Digital.
processing...

Welcome to Webmonkey

A private profile page has been created for you.
As a member of Webmonkey, you can now:
  • edit articles
  • add to the code library
  • design and write a tutorial
  • comment on any Webmonkey article
Close
Webmonkey is a property of Wired Digital.

Sign In Information Sent

An e-mail has been sent to the e-mail address registered in this account.
If you cannot find it in your in-box, please check your bulk or junk folders.
Sign In
Webmonkey is a property of Wired Digital.

Understand AJAX

/skill level/
/viewed/
0 Times

Contents

Introduction

Modern users of web applications are impatient and they're right to be. How annoying is it when you are on a web page, you click the "submit" button and the whole damn page disappears only to return with your updated information. Why does the whole page have to be replaced?
The reality is that it does not. Modern AJAX-heavy apps such as Gmail have taught users using the web does not have to be so painful. AJAX offers the answer for this maddening situation.
If you are a web developer, you need to understand AJAX, how it works and why. This tutorial will show you how to build your own AJAX features.

What you'll need

AJAX, which stands for Asynchronous Javascript and XML, is not a beginner's technology. So, you will need to have already built at least one web application before you attempt to tackle an AJAX feature. Then again, if you're a hardcore, give it a try.

Steps

AJAX, An Introduction

Image:JJG.jpg

Jesse James Garrett of Adaptive Path

AJAX is a term coined by Mr. Jesse James Garrett of Adaptive Path to

describe a type of web programming that transfers information to and from the server without doing a server post.

This is not really new technology, rather it is a clever combination of

somewhat new and mostly existing technologies, such as JavaScript—the language many web programmers love to hate–and a special object pioneered by [holding my nose] Microsoft with CSS thrown into the mix.


  • AJAX is a large topic that could fill hundreds of slides.
  • In this tutorial, I intend only to present an introduction to AJAX.
  • This tutorial will not be comprehensive.
  • This tutorial will get you up and running with AJAX.

AJAX: A Quick Overview of How it Works

First we will cover the round trip of how AJAX works and then we will circle around and show how each of the steps work in detail.

1. A special Request object is created.

2. A JavaScript Function is Called.

3. An Asynchronous Request is sent.

4. The response eventually comes.

5. The HTML of the page is changed.


1. A special Request object is created.

There are inconsistencies in the way that different browsers implement this step. Therefore, we are forced to determine which browser the user is using before we decide which type of object to create.

2. A JavaScript Function is Called.

This can be called when the page first loads or at anytime after the page has been loaded. This can be triggered by some user-triggered event or by a status change.

3. An Asynchronous Request is sent.

Here, we send the request to a URL—also sending along parameters if we wish—and then registering a callback handler that will wait for the response.

4. The response eventually comes.

Actually, the callback handler that we register will receive several responses during the processing of the request. However, only a particular one—with a special status of "4"—will contain the response information we sought.

5. The HTML of the page is changed.

Finally, we pull out the information from the request that we need and use that to modify the HTML of our page. There are several ways of doing that, which we shall see.

AJAX: A Special Request Object is Created

When the page loads, it executes the JavaScript function:
createRequestObject().

Image:createRequestObject.jpg

In other words, when this page is loaded for the first time, the following line of code is executed:

var http = createRequestObject();
That means, when the page has been loaded, the variable http will be initialized. The function’s declaration is right above it. So, while we stare at the newly loaded page, this http object has already been created and it waits around for us to do something.

In the AJAX world, we have a problem. The primary object that AJAX relies on was implemented differently by different browsers such as MS IE, Mozilla Firefox, etc.
For example:

When the browser is InternetExplorer, the variable ro [return object] is initialized with this line:

ro = new ActiveXObject( "Microsoft.XMLHTTP" );


Otherwise, if the browser is any other kind, such as Firefox, Opera, Chrome or what have you, the ro variable is initialized with this line of code:


ro = new XMLHttpRequest();


There are many ways and 3rd-party libraries that address the problem of different browser implementations but for this example these two will suffice.


AJAX: A JavaScript Function is Called


  • AJAX is a driven by event logic. You ask AJAX to do something and that triggers an event.
  • If you want the event to be triggered right away when your web page has finished loading, then you can use the routine
<body onload="javascript; myEvent();"> style.
  • If you want the event to be triggered by a specific event that happens after the page has been loaded and the user does something, then you can use any of the traditional JavaScript events such as onClick(), onBlur(), etc.
  • After the page has loaded, we have the opportunity to press a button—not even a submit button—and trigger an onClick event.

Image:OnClick.jpg

And this method is triggered when the user clicks on this submit button:

Image:Submit.jpg

Now, we see the entirety of the Javascript methods that are involved:

Image:SendRequest.jpg


By the time the user has pressed the button that causes sendRequest() to be executed, the http variable has been created with a request object appropriate for the browser.

Image:SendRequest2.jpg


The second statement in this function– http.onreadystatechange–is where we assign the callback handler, which is the method that will handle the responses that will come back asynchronously.

Image:SendRequest3.jpg


Image:SendRequest3d.JPG


Image:SendRequest4d.JPG

The second line is a bit of JavaScript trickery. handleResponse is actually a JavaScript function. JavaScript allows us to assign a function like this event handler without using the open and close parenthesis () we expect to see as part of a function name.

AJAX: An Asynchronous Request is Sent


Image:SendRequest5a.jpg

Finally, we execute the send(). Notice the null argument. In this example we are simply sending a GET to the named Servlet. We are not sending any parameters in this request. If we had been sending parameters, they would be mentioned in the send().

Understand—this is an Asynchronous request. After we execute the send, our sendRequest() function will immediately return but that does not mean our results are ready.


  • As we saw from the previous slide, our request is sent—in this example—to a servlet.
  • Notice how we return our data—we are just writing to the HttpServletResponse’s output stream. Simple.

Image:SendRequest6a.JPG


AJAX: The Response Eventually Comes


  • One of the puzzling aspects of AJAX is the response. We will not get just one response—but many.
  • First we will get a response that says: "I'm working on it."
  • Then we will get a response that says: "I'm loading."
  • Then, "I'm finished loading."
  • Finally, after several unimportant intermediate responses, we get the one we were originally seeking.

In this example, we disregard any readyState value other than 4, which means our response data is ready.

Image:SendRequest7a.JPG


Image:SendRequest8a.JPG


What is the DOM?

  • When we think of a webpage, we consider its HTML structure, right?
  • If we’re more advanced, we think of the CSS styles that give it its look at feel.
  • Well, in the eyes of JavaScript, a webpage is a tree of structure known as the DOM or Document Object Model.
  • JavaScript views a webpage as objects with properties that can be manipulated using the DOM

  • The DOM is a tree structure of objects on a webpage that can be addressed using JavaScript to change the appearance or even the underlying HTML of an existing page.

  • This is a basic HTML page—the HTML structure at least.

Image:SendRequest9a.JPG


  • Normally, it's hard to see the DOM underlying a webpage but the Firefox browser comes with a neat tool that helps us see the actual DOM that was created for this page.

Image:SendRequest10.JPG


  • This is the DOM that Firefox created for our page.

Image:SendRequest11b.JPG


  • You can navigate your way through this DOM tree but most times we have a better way.
  • We assign a unique id to any element we want to access.
  • Any piece of HTML can have an id.

Image:SendRequest12.JPG


Image:SendRequest13.JPG


  • Then, in a JavaScript <script> block, we can get a handle on that id-identified element and work with it.

Image:SendRequest14.JPG

So, we grab that HTML node and use a cool feature called innerHTML to change the HTML within that node.


AJAX: The HTML of the page is changed.


  • So, following our onMouseOver event, our original HTML is changed into something else.

Image:SendRequest15.JPG


AJAX: An Elaboration of the Process


  • So far, we have seen an end-to-end example of an AJAX call.
  • From what has already been seen, you can do a complete AJAX request-response cycle.
  • But AJAX has a lot more complexity that we have omitted.

For example:

  • What happens if an error occurred?
  • Although the request may have a readyState == 4, that does not guarantee everything worked as intended.
  • To see if the request was successful, we need to look at the status. If the status == 200, then we know it worked.

Image:SendRequest16.JPG

  • If you recall a few slides back, we built HTML within our Servlet. Before we did a write() to the request object, we set the

request.setContentType( "text/html" );

  • In fact, it is more common to set the content type = text/xml.
  • Therefore, if you set the content type to text/xml, you need to actually write XML.

AJAX: Returning XML


  • If you want to return more than one piece of data using a single AJAX call, then you need to:
    • create XML,
    • signal that what you’re returning is XML
    • consume the XML correctly on your page.

  • In this example, we’re trying to bring back more than one item.
  • We start with the typical AJAX code to get started.

Notice that we set the content type to be "text/xml".
This method just gets the parameters from the request and places them in an object called StoreWeb.


Image:SendRequest17.JPG

The method executeQuery( user ) queries the database based on the parameters.
The method convertVendorToXML( theVendor ) takes the data we just got from the database and takes it from the Vendor object and creates a String XML file.
Finally, the statement writer.println( theVendorAsXML ) just writes the String that contains the XML to the PrintWriter output.

Image:SendRequest18.jpg


Image:SendRequest19a.jpg


  • This is the method that builds the XML.

Image:SendRequest20.JPG


  • The XML is created as a String and that’s written to the output stream.

Image:SendRequest21.jpg

  • The XML is written.

Image:SendRequest22.jpg


  • Back on the JSP where the original AJAX call was made, here is the code that consumes the XML we just wrote.

Image:SendRequest23.jpg

This is the first case where we are reading the XML. Notice how this is accomplished. The original XML had a node called SOURCE_NUM. This allows us to get the data that was between

<SOURCE_NUM>xxx</SOURCE_NUM>


Image:SendRequest24.jpg


  • Sometimes it’s not as easy as that. For example, if I wanted to recreate an HTML SELECT statement using AJAX, I would prefer to send down XML.
  • This is the XML I’m sending down from my Servlet.

<?xml version="1.0" encoding="ISO-8859-1"?> <SELECT>

 <OPTION>
   <VALUE>0</VALUE>
   -- Select --
 </OPTION>
 <OPTION>
   <VALUE>1</VALUE>
   My First Dropdown Caption
 </OPTION>
 <OPTION>
   <VALUE>2</VALUE>
   My Second Dropdown Caption
 </OPTION>

</SELECT>


  • So, you sometimes need to use responseText and, on the fly, convert it into XML. This works in IE.
Notice that I reverted to responseText in the beginning.

Image:SendRequest25.jpg

  • This page was last modified 15:08, 16 October 2008.
Edit this article
Reddit Digg
 
Subscribe now

Special Offer For Webmonkey Users

WIRED magazine:
The first word on how technology is changing our world.

Subscribe for just $10 a year