Ajax-Enabled
Rich Internet
Applications
© 2008 Pearson Education, Inc. All rights reserved.... 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. It’s going to be fun.
—Jesse James Garrett
Dojo is the standard library
JavaScript never had.
—Alex Russell
© 2008 Pearson Education, Inc. All rights reserved.To know how to suggest is the great art of
teaching. To attain it we must be able to
guess what will interest ...
—Henri-Fredreic Amiel
It is characteristic of the epistemological
tradition to present us with partial scenarios
and then to demand whole or categorical
answers as it were.
—Avrum Stroll
O! call back yesterday, bid time return.
—William Shakespeare
© 2008 Pearson Education, Inc. All rights reserved.OBJECTIVES
In this chapter you will learn:
» What Ajax is and why it is important for building
Rich Internet Applications.
= What asynchronous requests are and how they
help give web applications the feel of desktop
applications.
= What the xmLHttpRequest object is and how it’s
used to create and manage asynchronous
requests to servers and to receive asynchronous
responses from servers.
© 2008 Pearson Education, Inc. All rights reserved.OBJECTIVES
= Methods and properties of the xMLHttpRequest
object.
= How to use XHTML, JavaScript, CSS, XML,
JSON and the DOM in Ajax applications.
= How to use Ajax frameworks and toolkits,
specifically Dojo, to conveniently create robust
Ajax-enabled Rich Internet Applications.
= About resources for studying Ajax-related issues
such as security, performance, debugging, the
“pack-button problem” and more.
© 2008 Pearson Education, Inc. All rights reserved.Outline
15.1
15.2
15.3
15.4
15.5
15.6
15.7
15.8
15.9
15.10
Introduction
Traditional Web Applications vs. Ajax
Applications
Rich Internet Applications (RIAs) with Ajax
History of Ajax
“Raw” Ajax Example Using the xmLuttpRequest
Object
Using XML and the DOM
Creating a Full-Scale Ajax-Enabled Application
Dojo Toolkit
Wrap-Up
Web Resources
© 2008 Pearson Education, Inc. All rights reserved.15.1 Introduction
+ Usability of web applications has lagged behind compared to desktop
applications
+ Rich Internet Applications (RIAs)
— Web applications that approximate the look, feel and usability of desktop appli
— Two key attributes—performance and rich GUI
+ RIA performance
= Comes from Ajax (Asynchronous Java!
make web applications more responsive
+ Ajax applications separate client-side user interaction and server
communication, and run them in parallel, making the delays of
server-side processing more transparent to the user
+ “Raw” Ajax uses JavaScript to send asynchronous requests to the
server, then updates the page using the DOM
+ When writing “raw” Ajax you need to deal directly with cross-
browser portability issues, making it impractical for developing large-
scale applications
rript and XML), which uses client-side scripting to
2008 Pearson Education, Inc. All rights reserved.15.1 Introduction (Cont.)
+ Portability issues
— Hidden by Ajax toolkits, such as Dojo, Prototype and Script.aculo.us
— Toolkits provide powerful ready-to-use controls and functions that enrich web
applications and simplify JavaScript coding by making it cross-browser compatible
+ Achieve rich GUI in RIAs with
— Ajax toolkits
— RIA environments such as Adobe’s Flex, Microsoft’s Silverlight and JavaServer
Faces
— Such toolkits and environments provide powerful ready-to-use controls and functions
that enrich web applications.
* Client-side of Ajax applications
— Written in XHTML and CSS
— Uses JavaScript to add functionality to the user interface
+ XML and JSON are used to structure the data passed
between the server and the client
+ XMLHttpRequest
— The Ajax component that manages interaction with the server
— Commonly abbreviated as XHR. & >
2008 Pearson Education, Inc. All rights reserved.15.2 Traditional Web Applications vs.
Ajax Applications
* Traditional web applications
User fills in the form’s fields, then submits the form
Browser generates a request to the server, which receives the request and
processes it
Server generates and sends a response containing the exact page that the browser
will render
Browser loads the new page and temporarily makes the browser window blank
Client waits for the server to respond and reloads the entire page with the data
from the response
« While a synchronous request is being processed on the
server, the user cannot interact with the client web
browser
* The synchronous model was originally designed for a web
of hypertext documents
some people called it the “brochure web”
model yielded “choppy” application performance
2008 Pearson Education, Inc. All rights reserved.2 6
3 Process |_| Generate Process Generate
3 request response. request response
¥
7
3
Request | Request 2|
4
4 8
gu
3S
3
Fig. 15.1 | Classic web application reloading the page for every user interaction.
© 2008 Pearson Education, Inc. All rights reserved.15.2 Traditional Web Applications vs.
Ajax Applications (Cont.)
¢ In an Ajax application, when the user interacts with a
page
— Client creates an XMLHttpRequest object to manage a request
— XMLHttpRequest object sends the request to and awaits the response from the
server
— Requests are asynchronous, allowing the user to continue interacting with the
application while the server processes the request concurrently
— When the server responds, the XMLHttpRequest object that issued the request
invokes a callback function, which typically uses partial page updates to display
the returned data in the existing web page without reloading the entire page
+ Callback function updates only a designated part of the
page
+ Partial page updates help make web applications more
responsive, making them feel more like desktop
applications
2008 Pearson Education, Inc. All rights reserved.12
3 Process Generate Process Generate
3 request | [| response request 2 |] response
5| cate data |7
2 4
ser interaction initiates Partial
asynchronous request page update
Request object |_/ g i
Callback function _#
Response processing
Request object
Callback function
Response processing
Client
Partial User interaction initiates
page update asynchronous request
Fig. 15.2 | Ajax-enabled web application interacting with the server asynchronously.
© 2008 Pearson Education, Inc. All rights reserved.15.3 Rich Internet Applications (RIAs)
with Ajax
* Classic XHTML registration form
— Sends all of the data to be validated to the server when the user clicks the
Register button
— While the server is validating the data, the user cannot interact with the page
— Server finds invalid data, generates a new page identifying the errors in the form
and sends it back to the client—which renders the page in the browser
— User fixes the errors and clicks the Register button again
— Cycle repeats until no errors are found, then the data is stored on the server
— Entire page reloads every time the user submits invalid data
+ Ajax-enabled forms are more interactive
— Entries are validated dynamically as the user enters data into the fields
— Ifa problem is found, the server sends an error message that is asynchronously
displayed to inform the user of the problem
— Sending each entry asynchronously allows the user to address invalid entries
juickly, rather than making edits and resubmitting the entire form repeatedly
until all entries are valid
— Asynchronous requests could also be used to fill some fields based on previous
fields’ values (e.g., city based on zipcode)
2008 Pearson Education, Inc. All rights reserved.14
2) A sample registration
form in which the user has
‘not fle inthe required
fields, but attempts to
submis the for anyway
by clicking Register
(MESES 1 seeg orem ae a scin
(O Nntowe vie
Fig. 15.3 | Classic XHTML form: User submits entire form to server, which
validates the data entered (if any). Server responds indicating fields with
invalid or missing data. (Part 1 of 2.)
© 2008 Pearson Education, Inc. All rights reserved.15
b) The server responds by
indicating al the form files
with missing or invalid data
The user must corect the
problems and resubmit the
entire form repeatedly until
all errors are corrected,
[O Wws Vn BOTScuy Ve or ate ear
0 Winns?
omcoss
ral
Otte
==
Fig. 15.3 | Classic XHTML form: User submits entire form to server, which
validates the data entered (if any). Server responds indicating fields with
invalid or missing data. (Part 2 of 2.)
© 2008 Pearson Education, Inc. All rights reserved.16
\Go- mms Bl c= fa
ate @ @avaus 628806" O=r-|
‘This is @ sample registration form
Pee ti a ets ond ces Retr
xD)
> = 1
x= = 1
ED ere] toe rtert in ea eaten ces
(0 tome ee
(© toe
ommorx
om
Fig. 15.4 | Ajax-enabled form shows errors asynchronously when user moves to another field.
© 2008 Pearson Education, Inc. All rights reserved.15.4 History of Ajax
* The term Ajax was coined by Jesse James Garrett of
Adaptive Path in February 2005, when he was presenting the
previously unnamed technology to a client
+ Ajax technologies (XHTML, JavaScript, CSS, dynamic
HTML, the DOM and XML) have existed for many years
+ In 1998, Microsoft introduced the XMLHttpRequest object
to create and manage asynchronous requests and responses
* Popular applications like Flickr, Google’s Gmail and Google
Maps use the XMLHttpRequest object to update pages
dynamically
+ Ajax has quickly become one of the hottest technologies in
web development, as it enables webtop applications to
challenge the dominance of established desktop applications
© 2008 Pearson Education, Inc. All rights reserved.18
15.5 “Raw” Ajax Example using the
XMLHttpRequest Object
+ XMLHttpRequest object
= Resides on the client
= _ Isthe layer between the client and the server that manages asynchronous requests in Ajax applications
= Supported on most browsers, though they may implement it differently
To initiate an asynchronous request
= Create an instance of the XMLHttpRequest object
— Use its open method to set up the request, and its Send method to initiate the request
When an Ajax application requests a file from a server, the browser
typically caches that file
— Subsequent requests for the same file can load it from the browser’s cache
Security
— XMLHttpRequest object does not allow a web application to request resources from
servers other than the one that served the web application
— Making a request to a different server is known as cross-site scripting (al
= You can implement a server-side proxy—an application on the web application’s web
server—that can make requests to other servers on the web application’s behalf.
When the third argument to XMLHttpRequest method open is
true, the request is asynchronous
o known as XS
2008 Pearson Education, Inc. All rights reserved.Performance Tip 15.1
When an Ajax application requests a file from
a server, such as an XHTML document or an
image, the browser typically caches that file.
Subsequent requests for the same file can load
it from the browser’s cache rather than
making the round trip to the server again.
© 2008 Pearson Education, Inc. All rights reserved.20
Software Engineering Observation 15.1
For security purposes, the XMLHttpRequest object doesn’t allow a web
application to request resources from domain names other than the one
that served the application. For this reason, the web application and its
resources must reside on the same web server (this could be a web server
on your local computer). This is commonly known as the same origin
policy (SOP). SOP aims to close a vulnerability called cross- scripting,
also known as XSS, which allows an attacker to compromise a website’s
security by injecting a malicious script onto the page from another domain.
To learn more about XSS visit en.wikipedia.org/wiki/XSS. To get
content from another domain securely, you can implement a server-side
proxy—an application on the web application’s web server—that can make
requests to other servers on the web application’s behalf.
2008 Pearson Education, Inc. All rights reserved.2
15.5 “Raw” Ajax Example using the
XMLHttpRequest Object (Cont.)
An exception is an indication of a problem that occurs during a program’s
execution
Exception handling enables you to create applications that can resolve (or
handle) exceptions—in some cases allowing a program to continue executing
as if no problem had been encountered
try block
Enclose code that might eause an exeeption and code that should not execute fan exception oecurs
— Consists of the keyword try followed by a block of code enclosed in curly braces ({})
When an exception occurs
= ery block terminates immediatly
= catch block catches (Le, receives) and handles an exception
catch block
— Begins with the keyword catch
= Fotlowed by an exception parameter in parentheses and a block of code enclosed in curly braces
Exception parameter’s name
~ Enables the catch block to interact with a eaught exception object, which contains name and message properties
A callback function is registered as the event handler for the
XMLHttpRequest object’s onreadystatechange event
= Whenever the request makes progress, the XMLHttpRequest calls the onreadys tatechange event handler.
= Progress is monitored by the readyState property, which has a value from 0 to4
~ Thevalue 0 indicates that the request isnot initialized and the value 4 indicates that the request is complete
2008 Pearson Education, Inc. All rights reserved.BRSBRRS
27
Ses
Outline
echcontent
pla The program attempts to execute |m™
eS eereae ence the code in the try block. an |
«box { border: 1px solid black: exception occurs, the code in the
padding: 0px } catch block will he executed
61
65
69 9 src
70 “http: //test.dei tel . com/examp]es/iw3htp4/aiax/thumbs /vbhtp3.jpa'
n onmouseover = 'getcontent( "vbhtp3.html" )'
n onmouseout = 'clearcontent()'/>
73
Qutline
Switchcontent
shtml
Gof 5)
© 2008 Pearson Education,
Inc. All rights reserved,
81 _adhiveclassi=smiboxtetdi=ntcontentaneallsanbsmte/cive
2 fate —_]| This div is updated with the ‘Switchcontent
ent description of the book that the | «htm
mouse is currently hovering over
7
78
79
80
(ofS)
2) User hovers over C+ How to Program book cover image, causing an asynchronous request tothe server to obtain the
book's description. When the response is received. the application perfims a partial page update to display the descipton
(C++ How To Program 60 ataon
+ Bay oflow, cary developed early clases sad ey abject approach
«+ lnepoted cave sacs Grughnt he book echng he Tee cans (Chapter 9) he
“Employ elas (Chapters 12 ad 15) ade GeadeBok cas (Chapters 3-7)
© 2008 Pearson Education,
Inc. All rights reserved,26
Qutline
1) Ua es oto a Pao bck Cre weg uc te ects ts
DOs (rein ex ime lI) |
i 4 [ese cecatimenn,, [=] =~ fe Ere Grae —
(of 5)
ava How to Program 7th Edition cade ol ofthe cone pedagogic mai om Java
“How to Program, 6 wpdeed to the foctcming lava Standard Editon 6 Teva SES,
(codenamed "Ma. Check ut the complete Tate of Contents, Here's some of he
ook’ ey eae:
+ Update te ete bosk othe new Java Standard Raion 6 (Masta)
+ Aten to key sftvare eaaceng community concep, sch as Web 20, SOA.
‘web serizes.open source software, dsn pats, mass, refactoring ond many
+ Cerf cordate with our aw Java, Web 2.0, Af, an Propramning
Projeas Resoues Cotes
+ New Ajet-enabled, even diven web appicationsdevelopmet with JavaServer Faces
© 2008 Pearson Education,
Inc. All rights reserved,27
Lied ssa peered) aie
onreadystatechange Stores the callback function—the event handler that gets called when
the server responds.
readystate Keeps track of the request’s progress. It is usually used in the callback
function to determine when the code that processes the response should
be launched. The readyState value 0 signifies that the request is,
uninitialized; 1 signifies that the request is loading; 2 signifies that the
request has been loaded; 3 signifies that data is actively being sent from
the server; and 4 signifies that the request has been completed.
responseText ‘Text that is returned to the client by the server.
responseXML If the server’s response is in XML format, this property contains the
XML document; otherwise, it is empty. It can be used like a document
object in JavaScript, which makes it useful for receiving complex data
(eg. populating a table).
status HTTP status code of the request. A Status of 200 means that request
was successful. A Status of 404 means that the requested resource
‘vas not found. A status of 500 denotes that there was an error while the
server was proccessing the request.
statusText Additional information on the request’s status. It is often used to display
the error to the user when the request fails.
. 15.6 | XMLHttpRequest object properties.
© 2008 Pearson Education, Inc. All rights reserved.LS tirels Ll Te)
‘open Initializes the request and has two mandatory parameters —
method and URL. The method parameter specifies the
purpose of the request—typically GET if the request is to
take data from the server or POST if the request will contain
a body in addition to the headers. The URL parameter
specifies the address of the file on the server that will
‘generate the response. A third optional boolean parameter
specifies whether the request is asynchronous—it’s set to
true by default.
send Sends the request to the sever. It has one optional parameter,
data, which specifies the data to be POSTed to the
server—it’s set to nu11 by default,
Fig. 15.7 | XMLHttpRequest object methods. (Part 1 of 2.)
© 2008 Pearson Education, Inc. All rights reserved.Method peer)
setRequestHeader Alters the header of the request. The two parameters specify
the header and its new value. It is often used to set the
content-type field.
getResponseHeader Returns the header data that precedes the response body. It
takes one parameter, the name of the header to retrieve, This
call is often used to determine the response’s type, to parse
the response correctly.
getAllResponseHeaders — Returns an array that contains all the headers that precede the
response body.
abort Cancels the current request.
Fig. 15.7 | XMLHttpRequest object methods. (Part 2 of 2.)
© 2008 Pearson Education, Inc. All rights reserved.30
15.6 Using XML and the DOM
+ When passing structured data between the server and the
client, Ajax applications often use XML because it
consumes little bandwidth and is easy to parse
¢ XMLHttpRequest object responseXML property
— contains the parsed XML returned by the server
+ DOM method createE]ement
— Creates an XHTML element of the specified type
- DOM method setAttribute
— Adds or changes an attribute of an XHTML element
+ DOM method appendchi 1d
— Inserts one XHTML element into another
¢ innerHTML property of a DOM element
— Can be used to obtain or change the XHTML that is displayed in a particular
element
© 2008 Pearson Education, Inc. All rights reserved.19
BRENRBRSBRVB
=e
au
Hel terss-:maliad
.
pulling images onto the Page
107
108
109 A11 Books
111 How ¥ Books
117 .NET Books.
120 Java, C, C++ Books
123 None
125
126
127
128
© 2008 Pearson Education,
Inc. All rights reserved,36
2) User clicks the All Books radio button to dsp althe book coves. The application sends an asynchronous quest to
the sever to ctain an XL document containg the lt of bok covet Nenames, When the esporseis ceed. the i
seis petoms pal pe apt thet look oes = Qutline
DO ite tennis aed lel me Bi
1 & Gomamqremtare LBB wre Om OR 7
en PulliImagesonto
{ANB © Sup Bess © Hors rpm Bats © NET Bass © C6 Bes © Mae
ie Page.htm]
(6 of 6)
ion sends an
1b) User clk the How to Program Books radio buon to select subset of book covers today. Applicat
asyvonous eauest othe sever o obtain an XML. document containing the appropriate subset of bok-coverfenames,
‘When the response is recelve.the application performs a paral page update a dspay the subse of ook coves.
© 2008 Pearson Education,
Inc. All rights reserved,37
15.7 Creating a Full-Scale Ajax-Enabled
Application
+ JSON (JavaScript Object Notation)
— Simple way to represent JavaScript objects as strings
— Analternative way (to XML) to pass data between the client and the server
* JSON object
— Represented as a list of property names and values contained in curly
braces
* Array
— Represented in JSON with square brackets containing a comma-separated
list of values
— Each value in a JSON array can be a string, a number, a JSON
representation of an object, true, false or nul
2008 Pearson Education, Inc. All rights reserved.38
15.7 Creating a Full-Scale Ajax-Enabled
Application
. JavaScript eval function
Can convert JSON strings into JavaScript objects
— To evaluate a JSON string properly, a left parenthesis should be placed at the
beginning of the string and a right parenthesis at the end of the string before the
string is passed to the eval function
— Potential security risk—evall executes any embedded JavaScript code in its
string argument, possibly allowing a harmful script to be injected into JSON
More secure way to process JSON is to use a JSON parser
SON strings
— Easier to create and parse than XML
— Require fewer bytes
— For these reasons, JSON is commonly used to communicate in client/server
interaction
+ When a request is sent using the GET method
— Parameters are concatenated to the URL
— URL parameter strings start with a ? symbol and have a list of parameter-value
bindings, each separated by an
¢ To implement type-ahead
— Can use an element’s onkeyup event handler to make asynchronous requests
2008 Pearson Education, Inc. All rights reserved.19
SBBRRBRRESRLB
39
ed
hem] xniins = "http: //mu.w3.0rg/1999/xhemI"> addressbook. htm]
(1of'ts)
script type = "sexe/ijavascripe" sre = “isonvis"s
52
338 i
339 Outline
340°
353°
354 First Name:
385
356 Last Name:
357
388 Address:
359
360 Street:
361
362 City:
365
366 zip: =e
© 2008 Pearson Education,
Inc. All rights reserved,367
368
369
370 Telephone:
372
373
374
375
377
378 div id = “success” class = "validator">
379
380