Anda di halaman 1dari 23

AJAX

Pragati Software Pvt. Ltd.


312, Lok Center, Marol-Maroshi Road
Andheri (East), Mumbai 400 059, India.

Tel.: +91-22-3091 0000 (100 Lines)


www.pragatisoftware.com
What Is Ajax? ........................................................................................................................................1
Defining Ajax......................................................................................................................................2
How Ajax is Different.........................................................................................................................2
Moving Forward .................................................................................................................................5
The Hidden Frame Technique .............................................................................................................7
Iframes....................................................................................................................................................8
XMLHttp................................................................................................................................................9
The Real Ajax ......................................................................................................................................10
Technologies Behind Ajax ..................................................................................................................11
Who Is Using Ajax?.............................................................................................................................12
Implementing Ajax..............................................................................................................................16
Performing Validation ........................................................................................................................19
What Is Ajax?
Ajax stands for Asynchronous Javascript And XML. Although strictly speaking Ajax itself is not
a technology, it mixes well-known programming techniques in an uncommon way to enable web
developers to build Internet applications with much more appealing user interfaces than those to
which we have become accustomed.

Ajax is an all-encompassing term surrounding the use of asynchronous HTTP requests initiated
by JavaScript for the purpose of retrieving information from the server without unloading the
page.

In February 2005, Jesse James Garrett, a founder of Adaptive Path (a Web interface and design
shop in San Francisco), coined the term Ajax in an article on their site. He said Ajax was
shorthand (but not an acronym) for "Asynchronous JavaScript and XML."

Here is the transcript of that article:

Ajax: A New Approach to Web Applications


by Jesse James Garrett
February 18, 2005

If anything about current interaction design can be called glamorous, its creating Web
applications. After all, when was the last time you heard someone rave about the interaction
design of a product that wasnt on the Web? (Okay, besides the iPod.) All the cool, innovative
new projects are online.

Despite this, Web interaction designers cant help but feel a little envious of our colleagues who
create desktop software. Desktop applications have a richness and responsiveness that has seemed
out of reach on the Web. The same simplicity that enabled the Webs rapid proliferation also
creates a gap between the experiences we can provide and the experiences users can get from a
desktop application.

That gap is closing. Take a look at Google Suggest. Watch the way the suggested terms update as
you type, almost instantly. Now look at Google Maps. Zoom in. Use your cursor to grab the map
and scroll around a bit. Again, everything happens almost instantly, with no waiting for pages to
reload.

Google Suggest and Google Maps are two examples of a new approach to web applications that
we at Adaptive Path have been calling Ajax. The name is shorthand for Asynchronous JavaScript
+ XML, and it represents a fundamental shift in whats possible on the Web.

AJAX 1
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-2850 1583, 2850 4130. Website: www.pragatisoftware.com.
Defining Ajax
Ajax isnt a technology. Its really several technologies, each flourishing in its own right, coming
together in powerful new ways. Ajax incorporates:

standards-based presentation using XHTML and CSS;


dynamic display and interaction using the Document Object Model;
data interchange and manipulation using XML and XSLT;
asynchronous data retrieval using XMLHttpRequest;
and JavaScript binding everything together.
The classic web application model works like this: Most user actions in the interface trigger an
HTTP request back to a web server. The server does some processing retrieving data,
crunching numbers, talking to various legacy systems and then returns an HTML page to the
client. Its a model adapted from the Webs original use as a hypertext medium, but as fans of
The Elements of User Experience know, what makes the Web good for hypertext doesnt
necessarily make it good for software applications.

This approach makes a lot of technical sense, but it doesnt make for a great user experience.
While the server is doing its thing, whats the user doing? Thats right, waiting. And at every step
in a task, the user waits some more.

Obviously, if we were designing the Web from scratch for applications, we wouldnt make users
wait around. Once an interface is loaded, why should the user interaction come to a halt every
time the application needs something from the server? In fact, why should the user see the
application go to the server at all?

How Ajax is Different


An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by
introducing an intermediary an Ajax engine between the user and the server. It seems like
adding a layer to the application would make it less responsive, but the opposite is true.

Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine
written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for
both rendering the interface the user sees and communicating with the server on the users behalf.
The Ajax engine allows the users interaction with the application to happen asynchronously
independent of communication with the server. So the user is never staring at a blank browser
window and an hourglass icon, waiting around for the server to do something.

AJAX 2
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Every user action that normally would generate an HTTP request takes the form of a JavaScript
call to the Ajax engine instead. Any response to a user action that doesnt require a trip back to
the server such as simple data validation, editing data in memory, and even some navigation
the engine handles on its own. If the engine needs something from the server in order to
respond if its submitting data for processing, loading additional interface code, or retrieving
new data the engine makes those requests asynchronously, usually using XML, without
stalling a users interaction with the application.

AJAX 3
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
AJAX 4
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Whos Using Ajax
Google is making a huge investment in developing the Ajax approach. All of the major products
Google has introduced over the last year Orkut, Gmail, the latest beta version of Google
Groups, Google Suggest, and Google Maps are Ajax applications. (For more on the technical
nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail,
Google Suggest, and Google Maps.) Others are following suit: many of the features that people
love in Flickr depend on Ajax, and Amazons A9.com search engine applies similar techniques.

These projects demonstrate that Ajax is not only technically sound, but also practical for real-
world applications. This isnt another technology that only works in a laboratory. And Ajax
applications can be any size, from the very simple, single-function Google Suggest to the very
complex and sophisticated Google Maps.

At Adaptive Path, weve been doing our own work with Ajax over the last several months, and
were realizing weve only scratched the surface of the rich interaction and responsiveness that
Ajax applications can provide. Ajax is an important development for Web applications, and its
importance is only going to grow. And because there are so many developers out there who
already know how to use these technologies, we expect to see many more organizations
following Googles lead in reaping the competitive advantage Ajax provides.

Moving Forward
The biggest challenges in creating Ajax applications are not technical. The core Ajax
technologies are mature, stable, and well understood. Instead, the challenges are for the designers
of these applications: to forget what we think we know about the limitations of the Web, and
begin to imagine a wider, richer range of possibilities.

Its going to be fun.

AJAX 5
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
JavaScript

Netscape Navigator was the first successful mainstream web browser, and as such, moved web
technologies along quickly. However, Netscape often was ridiculed by standards organizations
for implementing new technologies and extensions to existing technologies before the standards
were in place (much like Microsoft is being chastised today for ignoring existing standards in its
development of Internet Explorer). One such technology was JavaScript.

Originally named LiveScript, JavaScript was created by Brendan Eich of Netscape and included
in version 2.0 of the browser (released in 1995). For the first time, developers were able to affect
how a web page could interact with the user. Instead of making constant trips to the server and
back for simple tasks such as data validation, it became possible to transfer this small bit of
processing to the browser. This ability was very important at a time when most Internet users
were connected through a 28.8 Kbps modem, turning every request to the server into a waiting
game. Minimizing the number of times that the user had to wait for a response was the first major
step toward the Ajax approach.

Frames
The original version of HTML intended for every document to be standalone, and it wasn't until
HTML 4.0 that frames were officially introduced. The idea that the display of a web page could
be split up into several documents was a radical one, and controversy brewed as Netscape chose
to implement the feature before HTML 4.0 was completed. Netscape Navigator 2.0 was the first
browser to support frames and JavaScript together. This turned out to be a major step in the
evolution of Ajax.

When the browser wars of the late 1990s began between Microsoft and Netscape, both JavaScript
and frames became formalized. As more features were added to both, creative developers began
experimenting using the two together. Because a frame represented a completely separate request
to the server, the ability to control a frame and its contents with JavaScript opened the door to
some exciting possibilities.

AJAX 6
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
The Hidden Frame Technique
As developers began to understand how to manipulate frames, a new technique emerged to
facilitate client-server communication. The hidden frame technique involved setting up a frameset
where one frame was set to a width or height of 0 pixels, and its sole purpose was to initiate
communication with the server. The hidden frame would contain an HTML form with specific
form fields that could be dynamically filled out by JavaScript and submitted back to the server.
When the frame returned, it would call another JavaScript function to notify the original that data
had been returned. The hidden frame technique represented the first asynchronous
request/response model for web applications.

While this was the first Ajax communication model, another technological advance was just
around the corner.

Dynamic HTML and the DOM


Up to about 1996, the Web was still mainly a static world. Although JavaScript and the hidden
frame technique livened up the user interaction, there was still no way to change the display of a
page without reloading it. Then came Internet Explorer 4.0.

At this point, Internet Explorer had caught up with the technology of market leader Netscape
Navigator and even one-upped it in one important respect through the introduction of Dynamic
HTML (DHTML). Although still in the development phase, DHTML represented a significant
step forward from the days of static web pages, enabling developers to alter any part of a loaded
page by using JavaScript. Along with the emergence of cascading style sheets (CSS), DHTML
reinvigorated web development, despite deep disparities between the paths Microsoft and
Netscape followed during the early years of each discipline. Excitement in the developer
community was justified, however, because combining DHTML with the hidden frame technique
meant that any part of a page could be refreshed with server information at any time. This was a
genuine paradigm shift for the Web.

DHTML never made it to a standards body, although Microsoft's influence would be felt strongly
with the introduction of the Document Object Model (DOM) as the centerpiece of the standards
effort. Unlike DHTML, which sought only to modify sections of a web page, the DOM had a
more ambitious purpose: to provide a structure for an entire web page. The manipulation of that
structure would then allow DHTML-like modifications to the page. This was the next step
forward for Ajax.

AJAX 7
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Iframes
Although the hidden frame technique became incredibly popular, it had a downside one had to
plan ahead of time and write a frameset anticipating the usage of hidden frames. When the
<iframe/> element was introduced as an official part HTML 4.0 in 1997, it represented another
significant step in the evolution of the Web.

Instead of defining framesets, developers could place iframes anywhere on a page. This enabled
developers to forego framesets altogether and simply place invisible iframes (through the use of
CSS) on a page to enable client-server communication. And when the DOM was finally
implemented in Internet Explorer 5 and Netscape 6, it introduced the ability to dynamically create
iframes on the fly, meaning that a JavaScript function could be used to create an iframe, make a
request, and get the response all without including any additional HTML in a page. This led to
the next generation of the hidden frame technique: the hidden iframe technique.

AJAX 8
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
XMLHttp
The browser developers at Microsoft must have realized the popularity of the hidden frame
technique and the newer hidden iframe technique, because they decided to provide developers
with a better tool for client-server interaction. That tool came in the form of an ActiveX object
called XMLHttp, introduced in 2001.

One of the Microsoft extensions to JavaScript allowed the creation of ActiveX controls,
Microsoft's proprietary programming objects. When Microsoft began supporting XML through a
library called MSXML, the XMLHttp object was included. Although it carried the XML name,
this object was more than just another way of manipulating XML data. Indeed, it was more like
an ad hoc HTTP request that could be controlled from JavaScript. Developers had access to
HTTP status codes and headers, as well as any data returned from the server. That data might be
structured XML, pre-formatted swaths of HTML, serialized JavaScript objects, or data in any
other format desired by the developer. Instead of using hidden frames or iframes, it was now
possible to access the server programmatically using pure JavaScript, independent of the page
load/reload cycle. The XMLHttp object became a tremendous hit for Internet Explorer
developers.

With popularity mounting, developers at the open source Mozilla project began their own port of
XMLHttp. Instead of allowing access to ActiveX, the Mozilla developers replicated the object's
principal methods and properties in a native browser objectXMLHttpRequest. With both of the
major browsers supporting some form of XMLHttp, the development of Ajax-type interfaces
really took off and forced the fringe browsers, Opera and Safari, to support some form of
XMLHttp as well (both chose to do so natively with an XMLHttpRequest object, mimicking
Mozilla).

AJAX 9
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
The Real Ajax
Instead of the traditional web application model where the browser itself is responsible for
initiating requests to, and processing requests from, the web server, the Ajax model provides an
intermediate layer what Garrett calls an Ajax engine to handle this communication. An
Ajax engine is really just a JavaScript object or function that is called whenever information
needs to be requested from the server. Instead of the traditional model of providing a link to
another resource (such as another web page), each link makes a call to the Ajax engine, which
schedules and executes the request. The request is done asynchronously, meaning that code
execution doesn't wait for a response before continuing.

The server which traditionally would serve up HTML, images, CSS, or JavaScript is
configured to return data that the Ajax engine can use. This data can be plain text, XML, or any
other data format that you may need. The only requirement is that the Ajax engine can understand
and interpret the data

When the Ajax engine receives the server response, it goes into action, often parsing the data and
making several changes to the user interface based on the information it was provided. Because
this process involves transferring less information than the traditional web application model,
user interface updates are faster, and the user is able to do his or her work more quickly. The
following figure is an adaptation of the figure in Garrett's article, displaying the difference
between the traditional and Ajax web application models.

AJAX 10
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Technologies Behind Ajax
HTML/XHTML: Primary content representation languages
CSS: Provides stylistic formatting to XHTML
DOM: Dynamic updating of a loaded page
XML: Data exchange format
XSLT: Transforms XML into XHTML (styled by CSS)
XMLHttp: Primary communication broker
JavaScript: Scripting language used to program an Ajax engine

In reality, all these technologies are available to be used in Ajax solutions, but only three are
required: HTML/XHTML, DOM, and JavaScript. XHTML is obviously necessary for the display
of information, while the DOM is necessary to change portions of an XHTML page without
reloading it. The last part, JavaScript, is necessary to initiate the client-server communication and
manipulate the DOM to update the web page. The other technologies in the list are helpful in
fine-tuning an Ajax solution, but they aren't necessary.

There is one major component that Garrett neglected to mention in his article: the necessity of
server-side processing. All of the previously listed technologies relate directly to the client-side
Ajax engine, but there is no Ajax without a stable, responsive server waiting to send content to
the engine. For this purpose you can use the application server of your choice. Whether you
choose to write your server-side components as PHP pages, Java servlets, or .NET components,
you need only ensure the correct data format is being sent back to the Ajax engine.

AJAX 11
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Who Is Using Ajax?
Google Suggest
One of the first examples that developers cite when talking about Ajax is Google Suggest
(www.google.com/webhp?complete=1). The interface is simply a clone of the main Google
interface, which prominently features a text box to enter search terms. Everything appears to be
the same until you start typing in the textbox. As you type, Google Suggest requests suggestions
from the server, showing you a drop-down list of search terms that you may be interested in. Each
suggestion is displayed with a number of results available for the given term to help you decide

Gmail
Gmail, Google's free e-mail service, has been raved about as a marvel of client-server interaction
in the age of Ajax. When you first log in to Gmail, a user interface engine is loaded into one of
the few iframes the application uses. All further requests back to the server occur through this
user interface engine through an XMLHttp object. The data being transferred back and forth is
JavaScript code, which makes for fast execution once downloaded by the browser. These requests
serve as instructions to the user interface engine as to what should be updated on the screen.

AJAX 12
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Google Maps
The latest addition to Google's dominant Ajax web applications is Google Maps
(http://maps.google.com). Designed to compete with well-established mapping sites, Google
Maps uses Ajax to avoid reloading its main page at all.

Unlike other mapping web applications, Google Maps enables you to drag the map to move it in
various directions. The dragging code is nothing new to JavaScript developers, but the tiling of
the map and seemingly endless scrolling effect are another story. The map is broken up into a
series of images that are tiled together to make the appearance of a contiguous image. The
number of images used to display the map is finite, as creating new images every time the user
moves the map would quickly lead to memory problems. Instead, the same images are used over
and over to display different segments of the map.

A9
Amazon.com is world famous for being an online marketplace for just about anything, but when
it released a search engine, it did so with little fanfare and attention. The introduction of A9
(www.a9.com) showed off enhanced searching, enabling you to search different types of
information simultaneously. For web and image searches it uses Google to fetch results. It
performs searches of books on Amazon.com and movies on IMDb (Internet Movie Database).
Searches for Yellow Pages, Wikipedia, and Answers.com debuted in mid-2005.

AJAX 13
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Yahoo! News
he photo information and summary are retrieved from the server using XMLHttp and inserted
into the page dynamically. This is a perfect example of how Ajax can be used to enhance a web
page. Rather than making Ajax the primary usage mode, the Yahoo! News site is completely
usable without Ajax; the Ajax functionality is used only to add a more responsive user experience
in browsers that support it. Underneath is a semantically correct HTML page that is laid out
logically even without CSS formatting.

AJAX 14
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
AJAX 15
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Implementing Ajax
Performing Validation
A central tenant of usability says you should prevent errors from occurring, but barring that,you
should informyour users of errors as soon as possible. Before Ajax, Web-based applications had
to post the entire page to validate the data or rely on complex JavaScript to check the form. While
some checks are fairly simple to write in JavaScript, others just plain cant be done. Of course,
every validation routine you write on the client has to be rewritten on the server anyway since its
possible a user has JavaScript turned off. With Ajax, you no longer have to confine yourself to
simple client-side validations and duplicated logic. Now when you want to provide a more
responsive experience for your users, you can simply call the validation routine you wrote for the
server. In most cases, this logic will be simpler to write and easier to test, and its likely you can
rely on existing frameworks. When were asked where people should start using Ajax in their
applications, we typically recommend starting with validation. Chances are pretty good youve
got some JavaScript youd like to get rid of, and you can probably easily tie into some existing
server-side logic.

In this section, well show an example of one of the most common validations: dates. The HTML
for this example is pretty straightforward . You have a standard input box with an onchange()
event (of course, you could use whatever event you think is appropriate) that triggers the
validation method. You can see that youre calling the standard createXMLHttpRequest()
method and then sending the input value to the ValidationServlet servlet. The callback()
function gets the results from the server and then delegates to the setMessage() method, which
looks at the values to determine in which color the message should be displayed.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >


<html>
<head>
<title>Using Ajax for validation</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function validate() {
createXMLHttpRequest();
var date = document.getElementById("birthDate");
var url = "ValidationServlet?birthDate=" + escape(date.value);
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
AJAX 16
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var mes =
xmlHttp.responseXML
.getElementsByTagName("message")[0].firstChild.data;
var val =
xmlHttp.responseXML
.getElementsByTagName("passed")[0].firstChild.data;
setMessage(mes, val);
}
}
}
function setMessage(message, isValid) {
var messageArea = document.getElementById("dateMessage");
var fontColor = "red";

if (isValid == "true") {
fontColor = "green";
}
messageArea.innerHTML = "<font color=" + fontColor + ">"
+ message + " </font>";
}
</script>
</head>
<body>
<h1>Ajax Validation Example</h1>
Birth date: <input type="text" size="10" id="birthDate"
onchange="validate();"/>
<div id="dateMessage"></div>
</body>
</html>

AJAX 17
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
Dynamically Loading List Boxes

Web applications are often built using the wizard design philosophy, where each screen asks
the user for small bits of input and each successive pages data is built from the previous screens
input. This design pattern is quite useful for certain types of scenarios such as when the user is
performing a task that is best completed in a step-by-step, ordered manner. Unfortunately, too
many Web applications use this approach because they have to do so. Before Ajax techniques
were available, it was difficult if not impossible to update a page dynamically without refreshing
the entire page when certain parts of the page needed to change based on user input.

One technique to avoid constant page refreshes is to hide data on the page and display it as
needed. In the situation where the values in select box B are populated depending on the selected
value in select box A, the available values for select box B can be held in hidden select boxes.
When the selected value in select box A changes, JavaScript can determine which hidden select
should be displayed. That select box can then be made visible and the previous select box hidden.
Another variation is to dynamically populate the option elements of select box B with the
elements from a hidden list box. These techniques are useful, but their use is limited to scenarios
where the changes to the page are restricted to a finite set of choices based on the users input,
and even then the set choices must be relatively small.

Say youre building an online classified ads service for automobiles. Potential buyers search for
their desired autos by specifying a cars model year, make, and model. To avoid typographical
errors on a users part and reduce the number of dynamic validations required, youve decided
that the model year, make, and model input fields should all be select boxes and that the ads
should go back 25 model years.

Changing the selection in the model year select box or the manufacturer select box must change
the list of available models for that model year and manufacturer. Remember that with each
model year the number of available makes changes as new nameplates are introduced and old
ones are retired. Also keep in mind that the models available from each manufacturer vary from
year to year. With dozens of manufacturers and several models available per manufacturer per
model year, the number of combinations of model year, make, and model is staggering. That is
far too many combinations to populate the select boxes using JavaScript alone.

You can solve this problem easily using Ajax techniques. Each time the selection in the model
year or manufacturer select boxes changes, an asynchronous request is sent to the server
requesting the list of models available for that particular manufacturer in that particular model
year. The server is responsible for determining the list of models for the make and model year
requested by the browser. The server will most likely employ a high-speed data lookup
component, possibly implemented as a relational database, to perform the actual work of finding
the available models. Once the available models are found, the server packages them in an XML
file and returns them to the browser. The browser is responsible for parsing the servers XML
response and populating the model select box with the available models for the specified make
and model year. In this case, notice how well the view of the data is separated from the raw data.
The browser is solely responsible for rendering the view of the data. The server is responsible for
mining the raw data that must be rendered into a view on the browser.

AJAX 18
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
The following listing demonstrates how you can use Ajax techniques to dynamically create the
contents of one select box based on the values of two other list boxes. The examples use case is
the classified ads scenario described, where the selected values in a model year select box and a
manufacturer select box determine the contents of the model select box.

This example uses only four model years, three manufacturers, and four models available from a
certain manufacturer for a certain model year. Still, this makes 48 combinations of model year,
make, and model! This example would be impossible to do by hiding the list of models for every
model year and manufacturer combination and showing the appropriate list depending on the
selected manufacturer and model year values.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dynamically Filling Lists</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function refreshModelList() {
var make = document.getElementById("make").value;
var modelYear = document.getElementById("modelYear").value;
if(make == "" || modelYear == "") {
clearModelsList();
return;
}
var url = "RefreshModelList?"
+ createQueryString(make, modelYear) + "&ts=" + new
Date().getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function createQueryString(make, modelYear) {
var queryString = "make=" + make + "&modelYear=" + modelYear;
return queryString;
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
updateModelsList();
}
AJAX 19
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
}
}
function updateModelsList() {
clearModelsList();
var models = document.getElementById("models");
var results = xmlHttp.responseXML.getElementsByTagName("model");
var option = null;
for(var i = 0; i < results.length; i++) {
option = document.createElement("option");
option.appendChild
(document.createTextNode(results[i].firstChild.nodeValue));
models.appendChild(option);
}
}
function clearModelsList() {
var models = document.getElementById("models");
while(models.childNodes.length > 0) {
models.removeChild(models.childNodes[0]);
}
}
</script>
</head>
<body>
<h1>Select Model Year and Make</h1>
<form action="#">
<span style="font-weight:bold;">Model Year:</span>
<select id="modelYear" onchange="refreshModelList();">
<option value="">Select One</option>
<option value="2006">2006</option>
<option value="1995">1995</option>
<option value="1985">1985</option>
<option value="1970">1970</option>
</select>
<br/><br/>
<span style="font-weight:bold;">Make:</span>
<select id="make" onchange="refreshModelList();">
<option value="">Select One</option>
<option value="Chevrolet">Chevrolet</option>
<option value="Dodge">Dodge</option>
<option value="Pontiac">Pontiac</option>
</select>
<br/><br/>
<span style="font-weight:bold;">Models:</span>
<br/>
<select id="models" size="6" style="width:300px;">
</select>
</form>
</body>
</html>

AJAX 20
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.
The update of the page is driven by the onchange event of the make and model year select oxes.
Whenever the selected value in either of the select boxes changes, the browser sends an
synchronous request to the server. The request is sent with a query string containing the values f
the selected make and model year.

The RefreshModelList servlet accepts the request from the browser and determines the ist of
models for the specified make and model year. The servlet first parses the query string o
determine the requested make and model year. Once the requested make and model year ave been
determined, the servlet iterates over a collection of objects representing the available odel year,
manufacturer, and model combinations. If a particular objects model year nd manufacturer
properties match the requested model year and manufacturer, then the bjects model property is
added to the response XML string. Once all the models for the specified ake and model year have
been found, the response XML is written back to the browser.

Please note that in a real-world implementation the server-side piece would almost certainly not
rely on hard-coded values to populate the select box. The most likely implementation would
involve searching a high-speed database for the models available for the requested model year
and manufacturer.

AJAX 21
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. India.
Tel.: +91-22-3091 0000. Website: www.pragatisoftware.com.