You are on page 1of 30

Introduction to AJAX

Foreword:

This tutorial provides an introduction to AJAX; initially by explaining the different associated concepts and then presenting how to practically use AJAX in simple applications.

Basic Requirements:

You should have some basic knowledge about T!"#XT!" and Javascript before you start with AJAX .

What is AJAX Asynchronous JavaScript And XM ! AJAX is simply about Java$cript on the client %web browser& communicating with the server using X!". 't is based on Java$cript and TT( re)uests.

*y using AJAX+better+faster and easier to use web applications can be created.

AJAX is not a new programming language it ,ust introduces a new method of using the existing language standards.

A"a# We$ Mode%

The A,ax web model is based on the traditional web model with changes to the transmitted message on the web server and the web browser. The following diagram presents the AJAX web model.

'n the figure+the current T!" page displayed on the web browser has three parts. The two purple parts don-t need to be updated; only the yellow part needs to be.

Su$mittin& a Request .hat happens when the user submits a re)uest/

.hen user submits re)uest+the steps below occur se)uentially0 1. .eb browser re)uests for the content of ,ust the part of the page that it needs.

2. .eb server analy3es the received re)uest and builds up an X!" message which is then sent back to the web browser.

4. After the web browser receives the X!" message+it parses the message in order to update the content of that part of the page.

AJAX uses Java$cript language through TT( protocol to send#receive X!" messages asynchronously to#from web server.

Asynchronously means that data is not sent in a se)uence. Bene'its: AJAX brings to web applications new characteristics that are not available as standard in traditional web applications.

5ontinuous uploading+time is not wasted while waiting for page redraws and reloads 6eal7time updates+certain parts of the web pages are directly updated without re)uiring the whole page to updated. 8reater graphical interaction similar to desktop applications 9 drag and drop $tandard mechanism for the client to interact with the server and only send small xml fragments. Ro%e o' JavaScript
An T!" page has two components as shown in the figure below

(ocument )$"ect Mode% *()M+: : The .45 ;ocument <b,ect !odel is a platform and language neutral interface that allows programs and scripts to dynamically access and update content+structure and style of a document

: The T!" ;<! is the ;ocument <b,ect !odel for T!". The T!" ;<! defines a standard set of ob,ects for T!" and a standard way to access and manipulate T!" documents

: The T!" ;<! views T!" documents as a tree structure of elements. All elements+along with their text and attributes+can be accessed and manipulated through the ;<! tree

: The T!" code below shows ;<! *ody+=orm and 'nput ob,ects. The 'nput ob,ects are embedded in the =orm and the =orm is embedded in the *ody ob,ect

10 >html? 20 >head?>#head? 40 @0 >body? A0 >form idBClogin=ormC? D0 >input typeBCtextC idBCuserEameC#? F0 >input typeBCsubmitC idBCloginC valueBC"oginC#? G0 >#form? H0 >#body? 1I0 >#html?

The languages that can be used within the T!" ;<! to access ;<! ob,ects are Java+Java$cript+and J*$cript
Javascript

Java$cript is a scripting language that is supported and runs on almost all web browsers+such as 'nternet Kxplorer+!o3illa+=irefox+Eestcape and <pera.

Java$cript was designed to add interactivity to T!" pages

*y embedding Java$cript in an T!" page+parts of the ;ocument <b,ect !odel %;<!& within the T!" document can be updated.

,#amp%e: A Java$cript function will be added into the T!" code above to handle the onClick event of the "ogin button. As the user clicks the button+the notification message0L The name is required field and can not be empty will occur+if the user did not type in his name. The code as in following0

1: <html>

2:

<head>

3:

<script type=text/javascript>

4:

5:

function validateUser !

":

$: na%e= docu%ent&'et(le%ent)y*d +user,a%e!&value-

.:

if

na%e == !

/:

10: 4e e%pty!-

alert +12e na%e is re3uired field and can not

11:

12:

13:

14:

</script>

15: </head>

1":

1$: <body>

1.:

1/: <form id=lo'in6or%>

20: <input type=text id=user,a%e/>

21: <input type=su4%it id=lo'in value=7o'in on8lic9=validateUser()/>

22: </form>

23:

24: </body>

25: </html>

2":

-ow does AJAX wor. Ways to su$mit a request to the we$ server In the traditiona% we$ mode%/-0M Form e%ements are used to su$mit request to we$ server1 0he -0M code $e%ow is an e#amp%e o' an -0M 'orm:

10 >form idBClogin=ormC actionBClogin.,spC? 20 >input typeBCtextC idBCuserEameC#? 40 >input typeBCsubmitC idBCloginC valueBC"oginC ? @0 >#form?

The data of the sent message is combined with the data in the html form. 'n the above code+the content of the message is the value of the userEame textbox. After submitting the re)uest+the web browser then receives a new T!" page from the web server 'n the A,ax web model+there is another way+by using the X!" ttp!essage ob,ect to communicate with web server. The X!" ttp!essage ob,ect is used to send#receive messages to and from the web server. AJAX App%ication Some common steps that A"a# app%ication 'o%%ows:

The figure below describes the structure of T!" pages and a se)uence of actions in A,ax web application.0

2otice the three e%ements in the -0M pa&e:

M The handKvent%& Java$cript method+this method is used to handle events of a special T!" element

M X!" ttp6e)uest is an ob,ect supported by the web browser and runs as web client

M X!" message 7 message transferred between X!" ttp6e)uest ob,ect and web server is under X!" format

A"a# we$ app%ication 'o%%ows the sequentia% steps $e%ow3 the actions are a%so mapped 'rom the a$ove 'i&ure:

1. The Java$cript function handKvent%&t will be invoked when having an event occurred on the T!" element.

2. 'n the handKvent%& method+an instance of X!" ttp6e)uest ob,ect is created.

4. The X!" ttp6e)uest ob,ect organi3es an xml message within about the status of the T!" page+and then sends it to the web server.

@. After sending the re)uest+the X!" ttp6e)uest ob,ect listens to the message from the web server

A. The X!" ttp6e)uest ob,ect parses the message returned from the web server and updates it into the ;<! ob,ect

=or a demonstration of the steps+a code example is presented in the next section.
,#amp%es o' AJAX

*elow are two simple examples for using A,ax . <ne is an example for sending and getting a text message. The other one is an example for parsing an X!" message 5lick here to download the example about validating a user name. A text message is used in this example. 5lick here to download the example about car information. X!" message is used in this example. To see how to run the demonstrations+ look at the video here to find out how the A,ax example runs on different web browsers. 5lick here to download the demonstration for how an A,ax web application runs.

4ode ,#amp%e 'or creatin& an AJAX app%ication

'n this section+an example for A,ax web application is created step by step. The example is based on a simple login page that validates the username entered in. Requirements:

M The web application has a "ogin page containing username and password textboxes M .hen the user types in his name+ he will receive notifications about the status of the current value in the username textbox M 'f the current value is a beginning part of the string LJisual*uilderC+the user will receive a green notification L5ontinue..C

M 'f the current value is not a beginning part of the string+user will receive a red notification 7 L'nvalid input nameC M 'f the current value is e)ual to the string+ user will receive a blue notification LJalid input nameC This web application includes only a web page and a service running on web server.

0he we$ pa&e is -0M code with the em$edded JavaScript 'unctions: M JalidateNser%& to catch the user-s typing event on the username textbox and to send#receive the X!" message M Npdate;<!%& to parse the received message and update the status on the T!" page. The service running on the web server has the role to listen to the re)uest from the web browser then send back an appropriate X!" response. The diagram below describes the steps above in a se)uence of methods invoked0

There are three key points in creating an A,ax application+which are also applicable to this example0

: Nsing X!" ttp6e)uest ob,ect to send xml message to web server : 5reate a service that runs on web server to respond to re)uest : (arsing X!" ttp6e)uest ob,ect then update to ;<! ob,ect of the html page on client7side

5sin& XM -ttpRequest o$"ect to send #m% messa&e =irstly+the login page is presented %login.,sp& where the user types and receives the status immediately afterwards.

.hen the user is typing in the username textbox+the onOeyNp event is sent and the Java$cript function validateNse%& will be invoked+as written in following0

>input typeBPtextP idBPuserQnameP onOeyNpBPvalidateNser%&P?

'n the validateNser method+an instance of X!" ttp6e)uest will be created0 if %window.ActiveX<b,ect& R oX!"6e)uest B new ActiveX<b,ect%P!icrosoft.X!" TT(P&; S else

R oX!"6e)uest B new X!" ttp6e)uest%&; S

There are two ways of creating an instance of X!" ttp6e)uest ob,ect. They deal with the different kinds of browser+one for 'nternet Kxplorer and one for the other browsers such as !o3illa+$afari.

The instance of X!" ttp6e)uest ob,ect is used to send the X!" re)uest+and receive the response. *efore sending+it must be known where the service on web server located the message and the sending method. The code below is an example for setting up the re)uest0

var strNserEame B document.getKlement*y'd%PuserQnameP&.value; var strJalidation$erviceNrl B Puser.NserJalidator/NserEameBP T strNserEame;

oX!"6e)uest.open%P8KTP+strJalidation$erviceNrl+true&; oX!"6e)uest.onreadystatechange B update;<!; oX!"6e)uest.send%null&;

1. 0he )pen Method: The open method is to identify0 7 The N6" of destination service running on web server+ 7 $ending method is the http method+typical value is 8KT or (<$T but can also be KA; 7 *oolean value identifies that communication between X!" ttp6e)uest and web server is asynchronous or not

The property onreadystatechange is to specify the method to update the ;<! ob,ect of the T!" page. This method will be invoked immediately after receiving the response

from the web server. 'n the code above it-s the update;<!.

2. 0he Send Method: The send method is used to send a re)uest to the service specified in N6"+value of input parameter is content of the re)uest. 'n this case+the N6" parameter is used to tell the web server what is re)uired instead of the X!" message+so the X!" message is set as null.
4reate service respondin& to http request:

$econdly+on the server7side+within Java web application+we use one Java $ervlet as service running on web server. This servlet is to validate user name. 't has the do8et method to service http 8KT method0

public void do8et% ttp$ervlet6e)uest o6e)uest+ ttp$ervlet6esponse o6esponse& throws '<Kxception+$erverKxception R $tring strNserEame B o6e)uest.get(arameter%LNserEameC&; o6esponse.set5ontentType%Ptext#xmlP&; o6esponse.set eader%P5ache75ontrolP+Pno7cacheP&; if %LJisual*uilderC. index<f%strNserEame& BB I& R if %LJisual*uilderC.e)uals%strNserEame&& R o6esponse.get.riter%&.write%LJalidC&; S else R o6esponse.get.riter%&.write%L5ontinueC&; S S else R o6esponse.get.riter%&.write%L'nvalidC&; S S

The do8et checks user name posted by the client. 'f the is used name as a beginning part of LJisual*uilderC+the value of text response will be L5ontinueC+this means user is typing correctly. 'f the name is e)ual to LJisual*uilderC+the response will be LJalidC. owever+in other cases+the response

will be L'nvalidC. At the last+the do8et sends back this response to client.

6arsin& #m% response and update ()M o$"ect Kventually+after receiving the response+the ;<! ob,ect of the client html page will be updated. .e do that in the update;<! method0

function update;<!%& R if %oX!"6e)uest.ready$tate BB @& R if %oX!"6e)uest.status BB 2II& R str$tatus B oX!"6e)uest.responseText;

var status;iv B document.getKlement*y'd%PstatusP&; if %document.all& R status;iv B document.allUPstatusPV; S

if %str$tatus BB PJalidP& R status;iv.inner T!" B P>div styleBWcolor0greenW? Jalid user>#div?P; S else if %str$tatus BB P'nvalidP& R status;iv.inner T!" B P>div styleBWcolor0redW? 'nvalid user>#div?P; S else if %str$tatus BB P5ontinueP& R status;iv.inner T!" B P>div styleBWcolor0greenW? 5ontinue..>#div?P; S S S

The conditional line0 oX!"6e)uest.ready$tate B @ tells us that the X!" ttp6e)uest instance have ,ust received the response message and the line oX!"6e)uest.statusB2II which means that the service for response message has been done successfully.

The response message can be under text or xml format. 'n this method+parsing xml message is very simple0 by getting the text value of the responseText property. $till there is another way to get content of response+by parsing value of the responseX!" property. You could refer to the A,ax example for parsing xml for it. ,#amp%e:

The following are screenshots of running the example0 $tart by entering LJisualC for Jisual*uilder

'f LJisual5C is entered an invalid user message is displayed0

To get a valid user entered typeWJisual*uilderW0

,#amp%e 'or parsin& XM messa&e


This web example shows how to search books. .hen the user types into the category textbox+a list of book categories is received that have names near to value of the category textbox. 'f the value of the category textbox is found+the books textbox will display all books of this category 0he screen $e%ow shows: M M M Nser types category0 ,2ee e receives a suggestion0 J2KK J2KK exists+the books textbox displays all books of the category including0Jboss

server application+<racle J2KK+'*! .ebsphere

'n this example+ we used TT( messages between the web browser and web server as X!" messages

0here are three .ey points in usin& with: M M M 'n client7side+build and send X!" message 'n server7side+parse received X!" message and build to respond a new X!" message 'n client7side+parse the response X!" message and update to ;<!

Bui%din& response XM messa&e in server A Java $ervlet is used to check the re)uest from the client as in the first example. *ut this servlet is used in the (<$T method instead of the 8KT method. The do(ost%& method of the servlet is to examine re)uest in (<$T TT( method from

client+it looks like0

public void do(ost% ttp$ervlet6e)uest o6e)uest+ ttp$ervlet6esponse o6esponse& throws '<Kxception+$erverKxception R ## 8et category name passed by client $tring str5ategory B o6e)uest.get(arameter%PcategoryP& ## 8et output writer (rint.riter o.riter B o6esponse.get.riter%&; ## $et response in X!" format o6esponse.set5ontentType%Ptext#xmlP&; o6esponse.set eader%P5ache75ontrolP+Pno7cacheP&; ## <ut X!" message to client o.riter.print%getX!"6esponse!essage%str5ategory&&; S

This code shows that when each (<$T re)uest is caught+the servlet parses to get value of the category passed by the client and will look up for the list of books based on the given category+then respond it.

With XM messa&e/we notice in: M$et response message as X!" format instead of TKXT as in the first example M*uild response X!" message

The getX!"6esponse!essage%str5ategory& method is to build X!" message containing a suggestion and a list of related books. 't returns the message with a structure as below. 'n there+the suggestion node contains suggested categories and the books node contains a list of books it has.

>bookQresponse? >suggestion?>#suggestion? >books? >book?>#book? >book?>#book? >book?>#book? >#books?

>#bookQresponse? 6arsin& XM messa&e and update to ()M: Eow+after receiving X!" message+we need to parse it to get suggestions and the book list and then update to ;<!. The callback Java$cript update*ooks%& will do this. 'ts code includes two parts0 update suggestion and books The section code below is to get the root document of the X!" message0

## 8et X!" response message var X!"response B oX!"6e)uest.responseX!"; ## (oint to the XbookQresponse- node var doc6oot B X!"response.getKlements*yTagEame%PbookQresponseP&UIV;

'n order to get and update suggestion using the X!" structure shown above+we do as0

## 8et data of the $uggestion node var str$uggestion B doc6oot.childEodesUIV.first5hild.data;

## 8et a T!" ;<! ob,ect that need to be updated var suggestion T!";iv B document.getKlement*y'd%PsuggestionP&; f %document.all& R suggestion;iv B document.allUPsuggestionPV;

## ;isplay the received suggestion suggestion T!";iv.inner T!" B P>div?P str$uggestion P>#div?P;

.e update the book list similar to the given suggestion. owever+we should notice the way to get data from the tree node.

## 8et the books T!" ;<! ob,ect var book T!"Text B document.getKlement*y'd%PbooksP&; if %document.all& R book T!"Text B document.allUPbooksPV; S

## (oint to the *ooks node var o*ooks B doc6oot.childEodesU1V;

## (arse X!" message to build a book list var str*ooks B PP; for %var i B I; i > o*ooks.childEodes.length; i & R if %str*ooks BB PP& R str*ooks B o*ooks.childEodesUiV.first5hild.data; S else R str*ooks B str*ooks P+P o*ooks.childEodesUiV.first5hild.data; S S

## ;isplay the books list book T!"Text.value B str*ooks;

=or demonstration of running this application+you could refer to the Kxample of A,ax section
Xm%-ttpRequest o$"ect/how shou%d I use!

X!" ttp6e)uest ob,ect is a kind of web client that can retrieve and submit X!" data directly then convert retrieved X!" data into T!" content.

X!" ttp6e)uest ob,ect is supported in almost browser providers0

7 !icrosoft+it works as an ActiveX and is supported in 'nternet Kxplorer A.I or later as an ActiveX ob,ect

7 !o3illa+in =irefox1.I or later

7 Apple+in $afari1.2 or later

ow to create/ 5urrently+there are two ways to create ob,ect based on the browser provider0

For Microso't:

Jar oX!"6e)uest B new ActiveX<b,ect%L!icrosoft.X!" TT(C&;

For Mo7i%%a and Sa'ari

Jar oX!"6e)uest B new X!" ttp6e)uest%&;

)$"ect methods

=ollowings are the methods in the X!" ttp6e)uest ob,ect supported by $afari1.2+!o3illa and .indows 'K A.I or later

Method

(escription

abort%&

$tops the current re)uest

getAll6esponse eaders%&

6eturns complete set of headers %labels and values& as string

get6esponse eader%Lheader"abe 6eturns string value of a single header label lC&

This method is used to sets up a new re)uest to server.

open%LmethodC+LN6"C+U. async=lagU+CuserEameC U+CpasswordCVVV&

'ts parameters specify destination N6"+sending method and other optional attributes of a pending re)uest

$ending method is either (ost or 8et

send%content&

Transmit the re)uest+optionally with post7able string or ;<! ob,ect data

set6e)uest eader%LlabelC+Lvalue Assign a label#value pair to the header to be sent C& with a re)uest Fo%%owin& is the ta$%e o' a%% properties o' XMLHttpRequest o$"ect:

6roperty (escription

onreadyst Kvent handler for an event that atechange fires at every state change

<b,ect status integer0

I B un7initiali3ed

1 B loading 6eady$ta te 2 B loaded

4 B interactive

@ B complete

response The text that server sends back Text to respond to a re)uest.

;<!7compatible document response ob,ect of data returned from X!" server

Eumeric code returned by server

$tatus

@I@ B LEot =oundC

2II B L<kC

$tatusTex $tring message accompanying t the status code Ma.e asynchronous requests with JavaScript and AJAX

There are two ways to communicate with the client and the server; synchronous and asynchronous. "et-s take a look at them0

The se)uence diagram below is an example of the synchronous communication model0

'n this model+the client %browser or client application& makes a re)uest to the server then waits until it receives a response from the server before doing anything.

This process consumes unnecessary time. Suita$i%ity o' the synchronous and asynchronous mode%s Suita$i%ity: The synchronous model is not suitable with the kind of client application that often does interactions to the server. Kspecially within a web application because it makes them very slow. .ith asynchronous model+the client application does not consume much of the user-s time making him wait for the response. Therefore+the user feels in real7time while interacting. The se)uence diagram below shows the functioning of an asynchronous model0

This diagram shows that after sending the re)uest+the client can do something else instead of wasting his time waiting for the response and doing nothing. X!" ttp6e)uest ob,ect supports the asynchronous model. Nsing it in web application does not make you wait for the server to response after making a re)uest. The web application continues with other tasks rather than staying and listening to the response. Therefore+it prevents users from spending a long time waiting. X!" ttp6e)uest ob,ect has the open method to set asynchronous or not+like as in following0

var strJalidation$erviceNrl B LuserJalidation/userBJisual*ulderC; var bAsynchronous B true; var str ttp!ethod B L8KTC; oX!"6e)uest.open%str ttp!ethod+strJalidation$erviceNrl+bAsynchronous&; AJAX Framewor.s: There are many frameworks for A,ax+like J$= and $truts frameworks for $ervlet#J$(+developed to help developers more clearly and easily to write an A,ax pro,ect. 'n this section we will review several remarkable A,ax frameworks0

A,ax J$( Tag "ibrary

A,ax.Eet

<pen6ico

(rototype

$arissa

A"a# JS6 0a& i$rary: The A,ax Tag "ibrary is a set of J$( tags that simplifies the use of Asynchronous Java$cript and X!" %AJAX& in Java $erver (ages %J$(&.

=or more details+please refer to http0##a,axtags.sourceforge.net#

A"a#12et: A,ax.Eet is a library enabling various kinds of access from Java$cript to server7side.Eet. 't is able to access session data from Java$cript without source code changed on server7 side. 't also provides full class support for the returned values on the client7site-s Java$cript including ;ataTable+;ata$et+;ataJiew+Arrays and 5ollections

=or more details+refer to http0##weblogs.asp.net#mschwar3#

)penRico: 6ico provides a very simple interface for registering A,ax re)uest handlers as well as T!" elements or Java$cript ob,ects as response ob,ects. 't also provides interfaces for enabling web application to support drag and drop..

=or more details+refer to http0##openrico.org#

6rototype (rototype is a Java$cript framework including a solid A,ax library and a toolkit to simplify its use.

=or more details+refer to http0##prototype.conio.net#

Sarissa $arissa is a Java$cript A(' that summari3es X!" functionality in browser7independent calls. 't supports a variety of X!" technologies+including X(ath )ueries+X$"T+and seriali3ation of Java$cript ob,ects to X!"

=or more details+refer to http0##sarissa.sourceforge.net

You might also like