Está en la página 1de 208

WA1503 Comprehensive AJAX

WA1503 Comprehensive AJAX


Introduction to AJAX

(C) Web Age Solutions Inc. 2010

1-1

WA1503 Comprehensive AJAX

Objectives

Learn what AJAX is.


How does an AJAX based application
differ from a traditional web application.
What are the advantages of AJAX?
Learn the very basic AJAX API and have
a look at a few example code snippets.

(C) Web Age Solutions Inc. 2010

1-2

WA1503 Comprehensive AJAX

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML.


AJAX is an approach to developing web applications that differs
from the traditional way of developing applications.

In a traditional application, the user submits a form or clicks on a


link, the browser sends a HTTP request to the server, the server
replies with a fresh new HTML document that the browser renders
as a new page.

AJAX differs in two main ways:

The browser makes a HTTP request that may or may not be due to
a user action. For example, a clock application may automatically
make a HTTP request every second.
The reply from such a request does not contain a full new page. It
contains information that is used to update portions of the existing
page. For example, the clock application receives the current time
at the server as a part of the HTTP reply and updates the time
displayed in the page. The rest of the page remains as it is.

(C) Web Age Solutions Inc. 2010

1-3

WA1503 Comprehensive AJAX

A Simple Example

Learn how AJAX will do this application differently from a traditional


application.

Traditional Application
1. User selects an address.
2. A JavaScript function handles the onClick event of the list box.
3. The function submits the form. This causes the browser to send a HTTP request.
4. A Java Servlet or ASP page in the server side handles the HTTP request. It retrieves the
details of the selected address and returns a new HTML page. The page shows the
address details in the right hand side grey area.
Essentially, when the user selects an address, the entire page is replaced with a new page.
How AJAX Does it?
1. User selects an address.
2. A JavaScript function handles the onClick event of the list box.
3. The function uses certain JavaScript API to send a HTTP request. Note: the function does
not submit the form. The HTTP request is sent by invoking certain APIs that we will learn
shortly.
4. A Java Servlet or ASP page handles the request. It fetches the details about the selected
address. It returns a fragment of a HTML page that contains just the address details and
not anything else in the page (such as the list box).
5. Back in the browser side, a JavaScript function is called when the HTTP reply data is
ready. This function simply updates the content of the grey area to the right of the list box.

(C) Web Age Solutions Inc. 2010

1-4

WA1503 Comprehensive AJAX

The Old Way


JavaScript
event handler

Browser

Server

onClick
HTTP Request

HTTP Reply
(New page)

Here we see the timeline of how the address book will behave according to the
conventional way of programming.
When the user selects an address in the listbox, the browser invokes the
onClick event handler function. This function causes a HTTP request to be
sent by submitting the form (by calling the form.submit() function). The server
would reply by sending a full new page. The browser will render the new page
in place of the old.

(C) Web Age Solutions Inc. 2010

1-5

WA1503 Comprehensive AJAX

The AJAX Way


JavaScript
event handler

Browser

AJAX
Engine

Server

onClick
Send Request

Client side

HTTP Request

Update portions
of the page

Reply Data
Available

HTTP Reply
(HTML fragments)

Here we see the timeline of how the address book will behave according to the
AJAX way of programming.
When the user selects an address in the listbox, the browser invokes the
onClick event handler function. This function uses AJAX API to cause a HTTP
request to be sent. When the reply data comes back, the AJAX API invokes
another JavaScript event handler function. This function uses the data
available from the reply to update portions of the existing page.
What is Asynchronous about AJAX?
The AJAX Engine can invoke a JavaScript event handler function when the
reply data becomes completely available (or if an error occurs). This invocation
happens asynchronously at some time after the request was sent.

(C) Web Age Solutions Inc. 2010

1-6

WA1503 Comprehensive AJAX

Two Key Aspects of AJAX

A JavaScript function uses a special AJAX API


to send a HTTP request.

A conventional JavaScript function will do this by


submitting a form. But, this causes the browser to
replace the existing page with the page available
from the reply. We don't want to do that. Which
leads us to the next aspect.

We use the HTTP reply data to update parts


of the existing page.

Which means, the reply data contains only


fragments of a page and not an entirely new
page.

These two aspects of AJAX also form the two key goals of this course. We will
learn how to do these two tasks in increasingly sophisticated ways.

(C) Web Age Solutions Inc. 2010

1-7

WA1503 Comprehensive AJAX

What are the Advantages of


the AJAX Approach?

Two core advantages, both have to do with better


user experience:

Because a HTTP request updates parts of the existing page,


the display looks smooth and less jarring.
Because, the HTTP reply contains only small amounts of
page fragments, the interaction with the server is quick.

Indirect benefits:

XHTML and CSS2 make it possible to create very rich and


powerful web pages. When combined with AJAX, one can
create applications that can rival the productivity of a
desktop application. This includes drag and drop and
powerful new user controls (such as sortable grid).
AJAX does not require any browser plugins. Yet, it can
create applications that traditionally required Java or Flash.

The downside of a traditional application is that every HTTP request ends with
replacing the existing page with a new page. Essentially, the whole page is refetched and re-drawn. If the page is complex, this can lead to significant
delays in both obtaining the reply and rendering the page.
AJAX solves this problem. A HTTP requests results in small updates to the
existing page. This leads to a much better user experience. This also mimics
the desktop applications.

(C) Web Age Solutions Inc. 2010

1-8

WA1503 Comprehensive AJAX

AJAX Technologies

JavaScript The client side programming language. The AJAX


API is available as JavaScript objects and methods.
XHTML A full XML compliant version of the old HTML
language.

CSS2 This latest styling specification allows us to create


visually appealing applications.
All of these technologies are in the browser layer and available
from most modern browsers.

Proper XML compliance means, we can use a XML parser API such
as JavaScript Document Object Model (DOM) to manipulate the
contents of the page. This is how AJAX applications update parts of
a page.

AJAX can work with any server technologies.

We will learn about all three technologies in this class.

AJAX, XHTML and CSS2 are a powerful combination. To create feature rich
web applications that can match the functionality of a desktop application, you
will need to use all three technologies.
It is important to note here that AJAX does not depend on any specific server
technologies. We can build AJAX applications that can work with any type of
server code Java, ASP, PHP etc.

(C) Web Age Solutions Inc. 2010

1-9

WA1503 Comprehensive AJAX

The Basic AJAX API

The XMLHttpRequest object forms the heart


of the AJAX API.
This object is available as:

A native JavaScript class for Safari, Mozilla and


FireFox type browsers as well as IE7 or later.
An ActiveX object for Internet Explorer 6 or older.

This object is used to:

Make a HTTP request.


Obtain notification when the reply data is
completely available.
Obtain the reply data.

Here, we will discuss the XMLHttpRequest object very briefly. It will be


discussed again in greater detail in another chapter.

(C) Web Age Solutions Inc. 2010

1-10

WA1503 Comprehensive AJAX

Creating the XMLHttpRequest


Object
function createRequestSimple() {
var v;
try {
v = new XMLHttpRequest(); //Mozilla & IE7
} catch (e) {
v = new ActiveXObject("Microsoft.XMLHTTP");
}
if (v == null)
throw new Error("XMLHttpRequest not supported");
return v;
}

Here we see a simple JavaScript function that returns the XMLHttpRequest


object. First, it tries to create the native JavaScript object. If it fails, and the
system throws an exception and we try to create the ActiveX object.
In a later chapter, we will make this function a lot more sophisticated to deal
with more browser variations.

(C) Web Age Solutions Inc. 2010

1-11

WA1503 Comprehensive AJAX

The XMLHttpRequest Object


Basics

Methods

open(HTTP method, URL, asynchronous, user name, password) Initializes


the request object to make a HTTP request. The method does not actually
open any TCP/IP connection yet.
send(body) Sends the HTTP request body. For GET requests body is an
empty string. The method returns immediately if asynchronous is set to true
in open(). Otherwise it waits for all the reply to come back.

Properties

onreadystatechange Sets a JavaScript event handler function that will be


automatically invoked by AJAX at various times after the request has been
sent.
readyState The current state in the reply receipt phase. For example, 1
stands for loading and 4 stands for reply completely received.
status The HTTP reply code. For example, 200 means OK and 404 means
file not found.
responseText The reply document. Does not contain the reply headers.

The property names are case sensitive. In Mozilla based browsers, the case
must be correct. Note, how "onreadystatechange" is in all lower case, where
as the other properties use mixed case (camel case).

(C) Web Age Solutions Inc. 2010

1-12

WA1503 Comprehensive AJAX

Complete Example
<script type="text/javascript">
var req;
function startTest() {
req = createRequestSimple();
req.onreadystatechange = showReply;
req.open("GET", "response.txt", true);
req.send(null);
}
function showReply() {
if (req.readyState == 4 && req.status == 200) {
var div = document.getElementById("result");
div.innerHTML = req.responseText;
}
}
</script>
<button onclick="startTest();">Try It!</button>
<div id="result"></div>

When the Try It! button is pressed, the startTest() method is invoked. This
method creates a new XMLHttpRequest object by calling the
createRequestSimple() function. We have already seen how that function is
developed. Next, we set the onReadyStateChange property of the request
object to the showReply function. Then, we make a GET request for the
response.txt file. The value of the asynchronous flag is set to true. Next, we
send out the request with an empty body (GET requests do not have any body
text).
After the request is sent, the system automatically calls the showReply
function at various stages. In this example, we are only interested in the
successful completion of the reply. We check for the readyState to be 4 and
the status property to be 200. In that case, we, first, lookup the <div> object
with id "result". Then we set the contents of that <div> with the reply from the
server.
In this case, the content of response.txt is "Hello! This is a response from the
server".

(C) Web Age Solutions Inc. 2010

1-13

WA1503 Comprehensive AJAX

The Timeline
JavaScript
event handler

Browser

XMLHttpRequest

Server

startTest()
open()

Client side

send()
HTTP Request
HTTP Reply
(HTML fragments)
Update portions
of the page

showReply()

Here, we see the same AJAX request processing diagram from a previous
page. This time, the actual JavaScript method names are shown in bold face.
This diagram should make it very clear as to how the example works.
Just as a summary, the startTest() JavaScript function is registered as the
onclick event handler of the button. When the button is clicked, the sequence
of activities shown above take place.

(C) Web Age Solutions Inc. 2010

1-14

WA1503 Comprehensive AJAX

Review Questions
1.

2.
3.

4.

5.

6.

In what two ways does an AJAX application differ


from a traditional web application?
What are some advantages of the AJAX approach?
The ____________ object forms the heart of the
AJAX API.
What 3 technologies are typically used when
developing AJAX applications?
T/F: AJAX requires specific browser plug-ins to
work.
T/F: AJAX requires that the server-side technology
be Java.

(C) Web Age Solutions Inc. 2010

1-15

WA1503 Comprehensive AJAX

Review Answers
1.

2.

3.

The browser makes a HTTP request that may or may


not be due to a user action. Also, the reply from
such a request does not contain a full new page, but
instead a portion of the existing page.
A HTTP request updates part of the existing page
making the display look smooth and less jarring.
Also, the HTTP reply contains only a small amount of
information (i.e., page fragments), making the
interaction with the server quick.
XMLHttpRequest

(C) Web Age Solutions Inc. 2010

1-16

WA1503 Comprehensive AJAX

Review Answers
4.
5.

6.

JavaScript, XHTML, CSS2


False. AJAX does not require any plugins
(e.g., Java or Flash), which is one of the
reasons it's so attractive a technology.
False. AJAX can be used with any webbased, server-side technology that can
process and respond to an HTTP request, be
it a Servlet, a JSP, an ASP, a PHP, etc.

(C) Web Age Solutions Inc. 2010

1-17

WA1503 Comprehensive AJAX

WA1503 Comprehensive AJAX


XHTML

(C) Web Age Solutions Inc. 2010

2-1

WA1503 Comprehensive AJAX

What is XHTML?

It is the next generation browser markup language.

Will replace HTML 4. XHTML attempts to be backward compatible


with HTML 4.

XHTML is 100% XML syntax.


The advantages of XHTML are:

Since it is XML syntax, tools can easily parse and work with a
XHTML document.
Tools can easily validate the structure of a XHTML document.
The structure of the document can be easily manipulated by the
JavaScript DOM API to create powerful and rich client side
applications.

This is the primary reason for us to use XHTML with AJAX applications.

XHTML provides a way to extend the default markup language.


This can lead to more specialized languages.

In this chapter, we will cover the basic syntax and the main differences with
HTML 4. That should be sufficient for you to apply your existing knowledge of
HTML 4 to write XHTML documents.

(C) Web Age Solutions Inc. 2010

2-2

WA1503 Comprehensive AJAX

The DTD and MIME Type

There are three separate DTD files to capture three


types of structures.

XHTML strict Proper XHTML syntax. IE does not support


this very well.
XHTML transitional The syntax matches HTML 4 more
closely. Supported by all browsers. Recommended for now.
XHTML frameset Use this if you are using frames.

The MIME type of XHTML should ideally be


"application/xhtml+xml".

However, IE does not support this. So, keep using the MIME
type "text/html" until IE supports the actual MIME type.

The MIME Type Issue


The MIME type of a document is specified in the HTTP reply header "ContentType". The browser uses this to figure out how to render the document.
The official MIME type for XHTML is application/xhtml+xml. Apache 2.0 is
already configured to return this type for files with extension .xhtml or .xht. This
scheme works just fine with FireFox. However, IE does not recognize this
MIME type and asks the users to download the document.
To support IE, you need to keep using the "text/html" syntax and consequently
use the .html file name extension in the server.

(C) Web Age Solutions Inc. 2010

2-3

WA1503 Comprehensive AJAX

The Basic Syntax

The document should start with an XML preamble.

Next, the document must have a DOCTYPE element


and specify the DTD location.

<?xml version="1.0" encoding="UTF-8" ?>

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


Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">

Next, the root level element must be <html>

This and all other XHTML elements are defined in the


"http://www.w3.org/1999/xhtml" namespace.
It is recommended that you use an empty prefix for this
namespace to simplify the document.

Other DTD Locations


Strict:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Frameset:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

(C) Web Age Solutions Inc. 2010

2-4

WA1503 Comprehensive AJAX

The Basic Syntax


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
</body>
</html>

Here we see an example of a valid XHTML document.


Here we do not associate a prefix with the "http://www.w3.org/1999/xhtml"
namespace. If we did, the document would have been more complex to write.
For example:
<xht:html xmlns:xht="http://www.w3.org/1999/xhtml">
<xht:head>
</xht:head>
<xht:body>
</xht:body>
</xht:html>

(C) Web Age Solutions Inc. 2010

2-5

WA1503 Comprehensive AJAX

Embedding XHTML in a XML


Document
<?xml version="1.0" encoding="UTF-8"?>
<c:catalog xmlns:c='http://www.webagesolutions.com/schema'>
<c:product sku='P001'>
<c:title>Cheaper by the Dozen</c:title>
<c:description>
<! Switch to XHTML namespace -->
<p xmlns='http://www.w3.org/1999/xhtml'>
For details see <a
href="http://webagesolutions.com/products">online</a>.
</p>
</c:description>
</c:product>
</c:catalog>

Because, XHTML is pure XML, we can embed parts of it inside another XML
document (if that document's schema allows for it). In this example, we add a
<p> element inside the <c:description> element.

(C) Web Age Solutions Inc. 2010

2-6

WA1503 Comprehensive AJAX

Differences With HTML 4

In XHTML, all element names are in lower case.

All elements must be nested properly.

<p>Hello <b>World</b>.</p> - Valid


<p>Hello <b>World</p>.</b> - Invalid XHTML.

Some XHTML elements must have a body. They must have an


end tag.

<head> - Valid in XHTML.


<HEAD> - Valid in HTML 4.

<p>Hello World.</p> - Valid.


<p>Hello World. Invalid.

Some XHTML elements must not have any body.

<br/> or <hr/> - Valid


<br> or <hr> - Invalid

As you can see above, many syntaxes that are valid for HTML 4 are no longer
valid for XHTML.

(C) Web Age Solutions Inc. 2010

2-7

WA1503 Comprehensive AJAX

Differences With HTML 4

Attribute values must be quoted

An attribute must have a value

<option selected="selected"> - Valid


<option selected> - Invalid

In HTML 4, some elements (such as form and img) used the attribute
"name" and "id" interchangeably to identify the element.

<td colspan='2'> - Valid


<td colspan=2> - Invalid

In XHTML, only the "id" attribute should be used.


<form id="shipping" >

In HTML 4, values of enumerated attributes were case insensitive. In


XHTML, they must be in lower case.

<input type="text" id="t1"/> - Valid.


<input type="Text"> - Invalid for XHTML

The enumerated attributes must use a value from a specified list of possible
values. These values were case insensitive in HTML4. They must be in lower
case for XHTML.

(C) Web Age Solutions Inc. 2010

2-8

WA1503 Comprehensive AJAX

Embedding Scripts and Styles

The <script> and <style> elements must specify a "type"


attribute.

<script type="text/javascript"> </script>


<style type="text/css"> </style>

The body of these elements declared as #PCDATA.

That means characters like <, > and & will be treated specially.
Either use &lt;, &gt; and &amp; or escape the whole body using
<![CDATA[.
The latter is recommended as using &gt; etc in JavaScript could be
painful. See example below.
Note: Only FireFox enforces this behavior if application/xhtml+xml
MIME type is used. Since, we will not use that type, the use of
<![CDATA[ is strictly speaking not necessary but recommended.

<script type="text/javascript">
<![CDATA[
function startTest() {
var i = 10;
var j = 20;
if (i < j) {
alert("Special characters working");
}
}
]]>
</script>

(C) Web Age Solutions Inc. 2010

2-9

WA1503 Comprehensive AJAX

The Standard Attributes

Nearly all XHTML elements support a core set


of attributes. Most commonly used ones are:

id The identifier of the element. Must be unique


within the XHTML document. This id plays a vital
role in the DOM API as we will learn later.
style You can specify CSS2 styles for the
element.
class Alternatively, you can declare a style class
within a stylesheet and use the class name here.
This is recommended.
title The tooltip associated with the element.

(C) Web Age Solutions Inc. 2010

2-10

WA1503 Comprehensive AJAX

The <div> Element

Stands for a division or section.

A general purpose container.

Can contain many different types of children elements. Such


as <form>, <table> and other <div> elements.

This element plays a key role in AJAX programming.

Most browsers render the text in the body as a paragraph.

A <div> is used as a placeholder.


Results from a AJAX request is shown in a <div>.

The rendering behavior, position and size can be


heavily customized using CSS2.

This way, <div> can be used to write custom widgets for


the web pages.

<div id="d1">
<form id="f1" method="post" action="handle.jsp">

</form>
</div>

(C) Web Age Solutions Inc. 2010

2-11

WA1503 Comprehensive AJAX

The <span> Element

A placeholder similar to <div>.


Mostly used to style a length of text
differently from the rest of the paragraph.

<p>Hello <span class="w1">World</span></p>

Consequently, can not contain as many


different types of children as <div>
<span> can be used by an AJAX application
to alter contents within a paragraph.

<p>You have <span id="days"></span> days to


return the library book.</p>

(C) Web Age Solutions Inc. 2010

2-12

WA1503 Comprehensive AJAX

Review Questions
1.

2.
3.

4.

5.

An XHTML document is written using


_______ syntax.
What are some advantages of XHTML?
What DTD should you use when
creating XHTML documents? Why?
What are some differences between
XHTML and HTML 4?
What are the div and span tags used
for? How do they differ?

(C) Web Age Solutions Inc. 2010

2-13

WA1503 Comprehensive AJAX

Review Answers
1.
2.

XML
Advantages:

3.

XHTML documents can easily be parsed by tools designed


to work with XML, since they are XML
XHTML documents can be validated
The structure of an XHTML document can easily be
manipulated by the JavaScript DOM API to create powerful
and rich client side applications

You should use the XHTML transitional DTD because


it matches HTML 4 syntax very closely and is
currently supported by all browsers.

(C) Web Age Solutions Inc. 2010

2-14

WA1503 Comprehensive AJAX

Review Answers
4.

In XHTML, all element names are in lower case, all


elements must be nested properly, some elements
must have a body, some elements must not have a
body, attribute values must be quoted, and an
attribute must have a value. HTML 4 does not have
the above restrictions.
In HTML 4, some elements (e.g., form and img) use
the name and id attributes interchangeably to
identify the element, whereas in XHTML only the id
attribute should be used. In HTML 4, values of
enumerated attributes are case sensitive, whereas in
XHTML they must be in lower case.

(C) Web Age Solutions Inc. 2010

2-15

WA1503 Comprehensive AJAX

Review Answers
5.

The div and span tags both serve as


content placeholders and have an id attribute
associated with them. They differ from one
another in that a div tag is a block-level
element and a span tag is an in-line tag. A
block-level element is one that starts a new
line (paragraph), whereas an in-line element
is part of a line created by a block-level
element. Consequently, a div tag can
contain many more children than span tags,
including span tags.

(C) Web Age Solutions Inc. 2010

2-16

WA1503 Comprehensive AJAX

WA1503 Comprehensive AJAX


JavaScript DOM API

(C) Web Age Solutions Inc. 2010

3-1

WA1503 Comprehensive AJAX

What is DOM?

DOM stands for Document Object Model. According to this model, an XML
document is loaded into memory as a tree like hierarchy of elements.
DOM has dual purpose in a web browser:

Using the JavaScript DOM API, we can read data from and manipulate an XML
document. For example:

First, the XHTML or plain HTML document for a page is loaded as a DOM tree.
Second, you can construct an arbitrary XML document using the DOM API. We will
discuss this in a separate chapter.

Look up an element.
Create or remove elements.
Change the attributes of an element.

Simply put, this API allows us to alter the contents of a page that is currently
open in the browser.

Before DOM, one could only use document.write() to change the contents. As we will
see shortly, the DOM API allows for much more powerful page alteration.

The main purpose of the DOM API is to be able to alter a page after it has
been downloaded and rendered by the browser. We will cover that in details in
this chapter. The page doesn't have to be a valid XML (i.e., XHTML). It can be
a HTML document. The browser will internally convert the HTML to a valid
XML DOM document.
You can also parse or create any XML document using the DOM API. In other
words, DOM is not limited to an XHTML page. This will be covered in a
separate chapter.

(C) Web Age Solutions Inc. 2010

3-2

WA1503 Comprehensive AJAX

Element Hierarchy
<html>
<head><title>Hello</title></head>
<body>
<p>Hello world.</p>
<p class="w1" id="p1">How are you?</p>
</body>
The Document
</html>
<html>
<head>

<body>

<title>

<p>
Attribute:
class

<p>
Attribute:
id

The example above shows how the DOM API organizes the elements in a
XHTML document in a tree like structure. It is interesting to note that the
attributes of an element are also stored as children nodes.
At the very root of the hierarchy, we have a document object that represents
the entire XHTML document. The immediate next level child is usually the
<html> element. In this example, the <html> element contains two children a
<head> and a <body>.

(C) Web Age Solutions Inc. 2010

3-3

WA1503 Comprehensive AJAX

DOM Standardization

The DOM API is specified by W3C.


It has many language bindings C#, Java, C++ and JavaScript.
Most browsers conform to this standard to a great extent. There are
minor deviations at times.

These browser specific deviations are clearly labeled in this chapter. Here,
Mozilla stands for FireFox and Netscape. And, IE stands for Internet
Explorer.

Find DOM API documentation:

W3C spec: http://www.w3.org/TR/REC-DOM-Level-1/


IE has slightly different DOM API for a web page and generic XML:

XHTML DOM: http://msdn2.microsoft.com/enus/library/ms533050%28vs.85%29.aspx


DOM for XML: http://msdn2.microsoft.com/en-us/library/ms764730(VS.85).aspx

Mozilla: http://developer.mozilla.org/en/docs/Gecko_DOM_Reference

In this chapter, we deal with two types of browsers. Mozilla covers Netscape
and FireFox. We also cover Internet Explorer.

(C) Web Age Solutions Inc. 2010

3-4

WA1503 Comprehensive AJAX

The Document Object

Represents the root element of an XML (including HTML) document.


The HTML document currently loaded by the browser is available to
JavaScript as the global variable named document.

You can also load any other XML document using a URL or create a brand
new document from scratch.

Important properties of a document object:

documentElement returns the direct child element of the document


(which is usually <html>).
firstChild returns the first child of the document. See below on how this
may differ from documentElement.
body returns the <body> element in the document.
cookie returns a comma separated list of cookies.
forms, anchors and images These properties return an array of all
<form>, <a> and <img> elements in the document.
location or URL Both properties return the full URL of the document.

The documentElement and firstChild properties both return the top level
element of the document. For a valid XHTML document this will be the
<html> element.
However, different browsers behave differently in this regard.
1. documentElement IE and FireFox return the <html> element.
2. firstChild FireFox returns the <html> element. IE returns any comment or
<!DOCTYPE> element that may appear before the <html> element.
As a result, to get a hold of the <html> element, use the documentElement
property.
Example:
function showDocProperties() {
alert("documentElement: " + document.documentElement.nodeName);
}

(C) Web Age Solutions Inc. 2010

3-5

WA1503 Comprehensive AJAX

The document Object

Important methods:

getElementByID(id) Returns an element object given its


unique identifier. One of the most commonly used methods.
getElementsByName(name) returns an array of elements
with the given name.

Element names do not have to be unique.


This function is useful when you wish to get a list of similar
elements and do something with them. Such as make all error
messages blink.
For IE, only works for BUTTON, TEXTAREA, APPLET, SELECT,
FORM, FRAME, IFRAME, IMG, A, INPUT, OBJECT, MAP, PARAM
and META elements.

getElementsByTagName(tag) returns an array of elements


give their tag name. Use the tag name as "p", "div" etc.,
without the angle brackets.

In the example below, we find the elements by id or name and change their background color.
function findById(id) {
var e = document.getElementById(id);
if (e != null) {
e.style.backgroundColor = "yellow";
} else {
alert("Could not find element by ID: " + id);
}
}
function findByName(name) {
var list = document.getElementsByName(name);
if (list == null || list.length == 0) {
alert("Could not find element by name: " + name);
return;
}
for (var i = 0; i < list.length; ++i) {
var e = list[i];
e.style.backgroundColor = "red";
}
}
<p id="p1">This is a paragraph</p> findById("p1");
<div name="div1">Text</div> findByName("div1");

(C) Web Age Solutions Inc. 2010

3-6

WA1503 Comprehensive AJAX

The document Object

Important methods:

createElement(tag) Given a tag name (such as


"p" or "img"), returns a new element. To render
this element, it must be added as a child of an
existing element.
createTextNode(text) Creates a blob of text that
can be appended as body content of any other
element.
createAttribute(name) Returns a new attribute
node object. It must be associated with an
element later for it to have any effect. We will
learn how to set attribute of an element later.

Example:
In this example, we will write a function that adds a new line in this paragraph.
<p id="log_area"></p>
The following function creates new text node as well as new elements.
function logMessage(msg) {
var e = document.getElementById("log_area");
var txtNode = document.createTextNode(msg);
e.appendChild(txtNode);
var br = document.createElement("br");
e.appendChild(br);
}
//use the function from an XHTML document.
<p id="log_area">
<b>Log messages:</b><br/>
</p>
<button onclick="logMessage('TRACE: A sample message');">Log</button>

(C) Web Age Solutions Inc. 2010

3-7

WA1503 Comprehensive AJAX

Nodes and Elements

Each component of a DOM document is called a Node. This includes:

So, all Elements are also Nodes but not vice versa.

Comments
DOCTYPE declaration
Elements These are actual tags such as <p> and <form>.
Attributes of an element are also represented as a Node.
Element extends Node or inherits from Node in the Object Oriented
parlance.

In this chapter, we will focus on the properties, methods and events of


the Elements (which will include the behavior available from the Node
level).
All elements have a common set of behavior (properties, methods and
events). We will discuss them here.

Some complex elements, such as <form> and <table>, extend the Element
and add additional behavior. They will be discussed in a separate chapter.

The W3C DOM specification defines the behavior of the Node and Element
interface. JavaScript implements these interfaces. In this chapter, we will
discuss the behavior of the Element interface which extends Node. In a
separate chapter, we will discuss more advanced element types, such as a
table, that extends Element and adds more functionalities.

(C) Web Age Solutions Inc. 2010

3-8

WA1503 Comprehensive AJAX

The Element Object

An Element object is the core of all types of elements in a page.

An element object can be obtained by calling the document object's


getElementById, getElementsbyName or getElementsByTagName
methods.
Important properties:

Such as a form, img etc.

id The unique identifier.


childNodes Returns an array of children elements.
innerHTML The body content text of the element. This text may contain
other element tags. System will automatically create these child elements.
firstChild returns the first child element.
nextSibling returns the next element that has the same parent as this
element. You can iterate through all children by using firstChild in
conjunction with nextSibling. Alternatively, just call childNodes.
parentNode The parent node.

Manipulating the Contents of an Element


function fillHTML() {
var e = document.getElementById("div1");
e.innerHTML = "<p>Hello <span style='color: red;'>World</span></p>";
}
<div id="div1"></div>
<button onclick="fillHTML();">Fill HTML</button>
When the Fill HTML button is clicked, the fillHTML() function sets the
innerHTML property of the div1 element. This causes, system to automatically
create a <p> element and a <span> element as a child of the <p> element.
Eventually, the new <p> element is added to the <div> as a child.

(C) Web Age Solutions Inc. 2010

3-9

WA1503 Comprehensive AJAX

The Element Object

Important properties:

name The "name" attribute of the element. Non-unique. Not all


elements can have name.
nodeName Name of the node, such as FORM, P, IMG etc.

Returned in upper case by IE and FireFox if "text/html" MIME type is used. For
"application/xhtml+xml", lower case names are returned.

nodeType Integer value indicating the nature of the node. See list
below.
textContent (Mozilla), innerText (IE) The body text of an element. The
difference from innerHTML is that, tags for all child elements are stripped
out.
ownerDocument The document object that eventually owns this
element.
style Returns the style object. More on style object later.
className The name of the style class of the element.
parentNode Returns the node this element's parent.

Common Node Types


Element node = 1. Regular elements such as <p> and <form>
Attribute node = 2. Element attributes, which are also nodes.
Text node = 3. A node that contains the body text of the node's parent
element.
Comment Node = 8. XML comment.
Document Node = 9. The document itself.
The textContent/innerText Property
<p>Hello <span style="color: red">World</span></p>
The textContent of the <p> element is: "Hello World".

(C) Web Age Solutions Inc. 2010

3-10

WA1503 Comprehensive AJAX

The Element Object

Important methods:

appendChild(element) Adds a child element at the end of the list of children. If the element
being added is already in the DOM document, it will be first removed from its current parent.
Same goes for insertBefore.
insertBefore(element, beforeElement) Adds a new child element before the child element
beforeElement. Note: Element beforeElement must be a child of the current element for which
insertBefore is called. As a result, a common way to call insertBefore is:

sibling1.parentNode.insertBefore(sibling2, sibling1). sibling2 will be added before sibling1.

There is no insertAfter() function. Use this instead:

getElementsByTagName(tag) Returns an array of children elements that match the tag name
(such as "p" or "img").
getAttribute(name) Returns the value of an attribute given its name. IE has unusual behavior
for some properties. For example, use getAttribute("className") to get the "class" attribute.

sibling1.parentNode.insertBefore(sibling2, sibling1.nextSibling). sibling2 will be added after sibling1.

You can set extended attributes in HTML: <div foo="bar"/>. div.getAttribute("foo") will return "bar".

setAttribute(name, value) Sets the value of an attribute. You can set extended attributes not in
XHTML spec: div.setAttribute("foo", "bar").
setAttributeNode(attribute) Sets an attribute node object. Attribute nodes are created using the
createAttribute method of document.
getAttributeNode(name) returns the attribute node object given its name.

How to Use insertBefore?


Let us say that we wish to add a new child at the beginning of the list of children. There is no
equivalent of appendChild to do this. The following code will accomplish the same.
var div = document.getElementById("div1");
//We will add a new <p> as the first child of the div.
var currentFirstChild = div.firstChild;
var p = document.createElement("p");
div.insertBefore(p, currentFirstChild);
Working With Attributes
The getAttribute and setAttribute methods are easiest to work with.
function showAlign(id) {
var align = document.getElementById(id).getAttribute("align");
alert(align);
}
function setAlign(id, value) {
var align = document.getElementById(id).setAttribute("align", value);
}
<p id="p1">Hello World</p>
<button onclick="showAlign('p1');">Show Alignment</button>
<button onclick="setAlign('p1', 'left');">Left</button>
<button onclick="setAlign('p1', 'center');">Center</button>
<button onclick="setAlign('p1', 'right');">Right</button>

(C) Web Age Solutions Inc. 2010

3-11

WA1503 Comprehensive AJAX

The Element Object

Important methods:

removeChild(child) Removes a child element. The method returns the removed


element which stays in memory and can be added to another parent.
replaceChild(newChild, oldChild) The element replaces one child element with
another.
removeAttribute(name) Deletes the attribute of given name. The browser will use
a default value for the attribute if applicable.
hasChildNodes() Returns a true or false indicating if there is any child element.
hasAttributes() Returns true or false indicating if the element has any attribute.
cloneNode(deepCopy) Returns a replica of this element. If deepCopy is true, all
attributes and children elements are also copied. The newly created element must
be added to a parent element to be visible. If you need to create many elements
that have the same style and list of children, it will be faster to create a template
element first and simply clone it many times.

Example use of removeChild


function deleteAllChildren(parentId) {
var element = document.getElementById(parentId);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function reparent(oldParentId, newParentId, childId) {
var oldParent = document.getElementById(oldParentId);
var newParent = document.getElementById(newParentId);
var child = document.getElementById(childId);
child = oldParent.removeChild(child);
newParent.appendChild(child);
}

(C) Web Age Solutions Inc. 2010

3-12

WA1503 Comprehensive AJAX

Element Event Handlers

Nearly all elements support these event


handler properties:

Set the value of these properties to a function


object.

onblur, onclick, ondblclick, onfocus, onkeydown,


onkeypress, onkeyup, onmousedown,
onmousemove, onmouseout, onmouseover,
onmouseup and onresize.

There are three ways to do this. See below.

Event handling will be covered in more detail


in a separate chapter.

Setting Event Handler Function


function doSomething() {
alert("Event handler called");
}

Using attribute:
<button id="b1" onclick="doSomething();">Click me</button>
2. By setting property:
var btn = document.getElementById("b1");
btn.onclick = doSomething;
<button id="b1">Click Me</button>
3. Directly defining a function.
<script type="text/javascript">
function init() {
var btn = document.getElementById("b1");
btn.onclick = function() {
alert("Event handler called");
};
}
window.onload = init;
</script>
<button id="b1">Click Me</button>
Option 2 or 3 leads to cleaner HTML as the HTML body no longer has to specify JavaScript event handlers.

(C) Web Age Solutions Inc. 2010

3-13

WA1503 Comprehensive AJAX

The window Object

The JavaScript global variable window represents


the actual window that renders the DOM document.

A new window is created using the open method of


the window object.
Main properties:

Every window contains one document object.

document Returns the DOM document object.


frames Returns an array of Frame objects.
history Returns the browser's History object. Discussed
later.
location The URL of the page.
opener Returns the Window object that opened this
window. May be null if there are no opener.

(C) Web Age Solutions Inc. 2010

3-14

WA1503 Comprehensive AJAX

The window Object

Key methods:

open(URL, name, featureList) returns a new


window object and opens it.

URL The URL to show in the window. If empty string,


an empty document is shown.
name The unique name of the window. If a window by
that name is already opened, system loads in the new
URL and returns that window object.
featureList A comma separate list of name=value pairs.
See list of common features below.
Example: var w = window.open("http://abc.com",
"news", "menubar=yes,location=yes,resizable=no");

Common Features
left, top The left and top coordinate of the window, in pixels, relative to the
desktop.
width, height Width and height of the content area of the window in pixels.
This does not include scrollbars, status bars, menu bars etc.
menubar If true, the menubar is shown.
toolbar If true, the toolbar is shown.
location If true, the address bar (showing the URL of the page) is shown.
status If true, the statusbar is shown.

(C) Web Age Solutions Inc. 2010

3-15

WA1503 Comprehensive AJAX

The window Object

Events

onload Fired after all elements of a document


has been loaded from the network or cache.
onunload Fired, before a page is unloaded and
the next page is loaded.
onresize Fired after the window is resized.
onfocus/onblur Fired when keyboard focus is
gained or lost by the window.

(C) Web Age Solutions Inc. 2010

3-16

WA1503 Comprehensive AJAX

The Frame Object

Represents a <frame> element within a


<frameset>
Key properties:

contentDocument The document rendered in the


frame. IE may not support this. Some browsers
may use the property name "document".
src The URL of the frame.
noResize if true, frame can not be resized.

(C) Web Age Solutions Inc. 2010

3-17

WA1503 Comprehensive AJAX

The History Object

Represents a browser's history.


Obtained using the history property of the window
object.
Properties:

Methods:

length Number of items in the history. Read only.


back() Goes to the previous page.
forward() Goes to the next page.
go(index) Goes to a page relative to the current page. For
example, go(-1) is same as back() and go(1) is same as
forward().
go(URL) Goes to a page in the history that matches the
given URL.

(C) Web Age Solutions Inc. 2010

3-18

WA1503 Comprehensive AJAX

Review Questions
1.

2.

3.

4.
5.

What does the JavaScript DOM API


allow you to do?
A browser parses an XHTML document
and builds a ____________________.
The _________ element represents the
root element in the element tree.
T/F: All nodes are elements.
What are some examples of objects
provided by the JavaScript DOM API?

(C) Web Age Solutions Inc. 2010

3-19

WA1503 Comprehensive AJAX

Review Answers
1.

2.
3.
4.

5.

The JavaScript DOM API allows you to alter the


contents of a page that is currently open in the
browser. Specifically, it allows you to look up an
element, create or remove elements, or change the
attributes of an element.
hierarchical tree of elements
document
False. Nodes can be comments, DOCTYPE
declarations, elements, or attributes of an element.
document, Element, window, Frame, and History

(C) Web Age Solutions Inc. 2010

3-20

WA1503 Comprehensive AJAX

WA1503 Comprehensive AJAX


AJAX API Details

(C) Web Age Solutions Inc. 2010

4-1

WA1503 Comprehensive AJAX

The Request Object

The request object forms the core and perhaps the only API
required to perform AJAX style asynchronous communication
with the server.
Currently, there are two separate but highly compatible
implementations of the request object.

Mozilla browsers and IE 7 have a built in XMLHttpRequest


JavaScript class.
Internet Explorer (older than IE 7) uses an ActiveX object that
implements the IXMLHTTPRequest interface.

W3C is now formally managing a specification for the


XMLHttpRequest interface.

In this chapter, first we will discuss the behavior of the request


object that is common between the two implementations. Later,
we will discuss features that are only available in one of them.

http://www.w3.org/TR/XMLHttpRequest/

The IE ActiveX request object specification is available at:


http://msdn2.microsoft.com/en-us/library/ms760305(VS.85).aspx.
Mozilla's and IE 7's XMLHttpRequest JavaScript class follows the W3C spec
fairly closely. For Mozilla, read the documentation for the class here:
http://developer.mozilla.org/en/docs/nsIXMLHttpRequest
http://developer.mozilla.org/en/docs/nsIJSXMLHttpRequest
For IE 7, read the documentation for the native request object here:
http://msdn2.microsoft.com/en-us/library/ms535874(VS.85).aspx

(C) Web Age Solutions Inc. 2010

4-2

WA1503 Comprehensive AJAX

Creating the Request Object

Due to the two different implementations of the request object, we


need to write browser dependent code to create a new request object.
To make things more complex, in a Windows machine, there may be
different versions of the request object implementation. Currently, the
list of Activex component names in increasing order of age goes as
follows:

MSXML2.XMLHttp.5.0
MSXML2.XMLHttp.4.0
MSXML2.XMLHttp.3.0
MSXML2.XMLHttp
Microsoft.XMLHttp

In IE, try to use the built in XMLHttpRequest class. In IE 7, this native


JavaScript class may be disabled by the user from the advanced
options dialog. In IE 6 or older the class is not available. In these
cases, we should create the latest version of the ActiveX request
object.
In the next page, we show how to do this.

In IE 7 and Mozilla, creating the native request object is very easy:


var req = new XMLHttpRequest();
The ActiveX request object can be created in any version of IE as follows:
var req = new ActiveXObject("MSXML2.XMLHttp.5.0");
In IE7 Internet Options dialog you can click the Advanced tab and uncheck the
"Enable native XMLHTTP support" to disable the built in JavaScript class. In
that case, you must use the ActiveX object.

(C) Web Age Solutions Inc. 2010

4-3

WA1503 Comprehensive AJAX

Creating the Request Object


function createRequest() {
var v;
try {
v = new XMLHttpRequest(); //Mozilla & IE 7
} catch (e) {
v = createActivexXMLHttp(); //IE 6 or older
}
if (v == null)
throw new Error("XMLHttpRequest not supported");
return v;
}
See implementation of createActivexXMLHttp() below.

//Create the best possible ActiveX request object


function createActivexXMLHttp() {
var aVersions = [ "MSXML2.XMLHttp.5.0",
"MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
"MSXML2.XMLHttp","Microsoft.XMLHttp"];
for (var i = 0; i < aVersions.length; i++) {
try {
var oXmlHttp = new ActiveXObject(aVersions[i]);
return oXmlHttp;
} catch (oError) {
//Do nothing
}
}
throw new Error("MSXML is not installed.");
}

(C) Web Age Solutions Inc. 2010

4-4

WA1503 Comprehensive AJAX

The Request Object

Properties:

onreadystatechange The event handler method that is invoked at various


times after a request has been sent.

readyState An integer value indicating the current state of the request


object.

The event handler method does not take any parameter.

0 Uninitialized. No HTTP request has been sent.


1 Open. The open() method of the request has been successfully called.
2 Sent. The HTTP request has been successfully sent. IE Native & ActiveX:
No reply data has been received yet. Mozilla: Request has been sent and reply
headers have been completely received.
3 Receiving. Some reply data has been received. In IE Activex, there is no
guarantee that all reply headers have been received.
4 Loaded. The entire reply body has been received.

status The HTTP reply status code. Available when readyState is 3 or 4. A


value of 200 indicates success. 404 indicates invalid URL.
statusText The textual code for the HTTP reply status. For example, "OK"
for status 200 and "Not Found" for 404. Available in readyState 3 or 4.

Example:
req.onreadystatechange = func;
//The event handler does not receive any parameter
function func() {
}

(C) Web Age Solutions Inc. 2010

4-5

WA1503 Comprehensive AJAX

The Request Object

Properties:

responseText Contains the reply body data. System converts the text into
16bit UNICODE from the source encoding.

Source encoding is set in the Content-Type HTTP reply header. If missing, UTF-8
is assumed.
Note: responseText does not include the reply headers.
Reply body is available in readyState 3 or 4 only. Otherwise, this property will
return empty string. If readyState is 3, this property will return the partial reply
data that is currently available. When the state changes to 4, all the reply data is
available.

responseXML A DOM document representing the reply body. This


property makes it easy to process a reply body that is a valid XML
document.

The HTTP reply MIME type must be "text/xml" or "application/xml" for the
request object to automatically parse the body and create the DOM document.
The DOM API, already discussed in the context of a XHTML document, also apply
to this DOM document.

The responseXML Property


If the HTTP reply MIME type is "text/xml" or "application/xml", the request object proceeds to
parse the reply body and construct a DOM document. This document is made available
through the responseXML property.
This property can significantly aid the client server communication. The server can reply with
an XML document which contains pure data and no XHTML markup. Upon receiving the reply,
we can navigate the DOM document and show the data using XHTML elements. This makes
the server code GUI neutral. We can control the look and feel entirely from the client side using
JavaScript.
For example, let us say, that we make a AJAX request for a list books that match a search
criteria. The server can reply an XML document for that request as follows:
<result>
<book isbn="XXXX" title="World of Fashion"/>
<book isbn="YYYY" title="Sailing Around the World"/>
</result>
As you can see, the reply contains no XHTML markup and hence totally GUI neutral. Later, we
will learn how to use the responseXML DOM document object to show the data from the reply
on the screen.

(C) Web Age Solutions Inc. 2010

4-6

WA1503 Comprehensive AJAX

The Request Object

Methods:

open(method, uri, async, user, password) Initializes the


request object to make a HTTP request. The method does
not actually open any TCP/IP connection yet. The readyState
goes to 1. See other details below.

method "GET", "POST" etc.


uri The path to be requested. Can be relative to the location
of the page from where the method is being called.
async If true, the send() method will return immediately after
sending the request. Otherwise, it will block until all the reply
data is received. Optional. Default is true.
user, password The user credentials used for basic
authentication. Optional. The credentials are sent only if the
server challenges after the first attempt by sending 401 Access Denied response.

The open Method


This method is called to initialize the request object and prepare it for the
send() method call. The send() method call actually makes a network
connection and performs client/server communication.
The readyState goes to 1 after open() is called. If, when open() is called, the
readyState is 4, system automatically resets the request object. Calling open()
at other states will have undefined consequences. It is always a good idea to
call abort() before re-using a request object.
Example
req.open("GET", "http://xyz.com/app/getProducts?catId=100"); //async by
default
req.open("GET", "getProducts?catId=100"); //Using relative path
req.open("GET", "getProducts?catId=100", false); //Synchronous
req.open("GET", "getProducts?catId=100", true, "bob", "villa"); //Log in

(C) Web Age Solutions Inc. 2010

4-7

WA1503 Comprehensive AJAX

The Request Object

Methods:

send(data) Makes a connect to the server and


sends a HTTP request. The method returns
immediately if the async flag to the open() call is
true. Otherwise, it waits for the reply to be
completely received.

data The request body data. Optional. Can be a string


or DOM document. In case of the latter, system will
serialize the DOM document as XML text. see details
below.
For GET requests, set data to null or empty string.
Mozilla requires this parameter, although IE and W3C
marks it as optional.

The send Method


Must be called when readyState is 1 (that is after a open() call). If data is a
string, it is converted to UTF-8 before using it in the request body. If the data is
a DOM document, system looks at the XML preamble (<?xml version="1.0"
encoding="UTF-8" ?>) and determines the encoding. If preamble can not be
found, UTF-8 is used.
System does not automatically send the "Content-Type" request header. None
of the browser do, even for regular requests (such as when user submits a
form). If you need to inform the server about the encoding of the request, you
need to set the Content-Type header by calling the setRequestHeader
method. This is shown below.
request.setRequestHeader("Content-Type", "application/x-www-formurlencoded; charset=UTF-8");
For GET requests, there is no need to send request body data. In that case,
the body parameter to send() can be omitted (for IE only). It can also be null or
an empty string.

(C) Web Age Solutions Inc. 2010

4-8

WA1503 Comprehensive AJAX

The Request Object

Methods:

setRequestHeader(name, value) Sets an HTTP


request header. Should be called between open()
and send().

name Name of the header, such as "Content-Type".


value The header value.

getResponseHeader(name) Returns the value of


a HTTP reply header. Can be called when
readyState is 3 or 4.

name The name of the header.

We have already seen an example of the setRequestHeader method. Here it


is again.
request.setRequestHeader("Content-Type", "application/x-www-formurlencoded; charset=UTF-8");
Using request header, we can control the caching behavior. We will discuss
this later.
Example of getResponseHeader.
if (request.readyState >= 3) {
var type = request.getResponseHeader("Content-Type");
}

(C) Web Age Solutions Inc. 2010

4-9

WA1503 Comprehensive AJAX

The Request Object

Methods:

getAllResponseHeaders() Returns the


entire HTTP reply header. This method is
not in the W3C specification but is
supported by both Mozilla and IE. Useful
for debugging purposes only.
abort() Terminates any network
connection and resets the request object to
an initial state (readyState of 0).

(C) Web Age Solutions Inc. 2010

4-10

WA1503 Comprehensive AJAX

Simple GET Example


<script language="javascript">
var request;
function sendAjaxRequest() {
if (request != null) {
request.abort();
} else {
request = createRequest(); //This function is shown earlier
}
request.onreadystatechange = showResult;
var url = "city.html";
request.open("GET", url, true);
request.send(null);
}
function isReplyReady(r) {
if (r.readyState != 4) {
return false;
}
if (r.status != 200) {
alert("HTTP reply failed with status: " + r.status);
return false;
}
return true;
}
function showResult() {
if (!isReplyReady(request)) {
return;
}
var div = document.getElementById("result");
div.innerHTML = request.responseText;
}
</script>

(C) Web Age Solutions Inc. 2010

4-11

WA1503 Comprehensive AJAX

Simple GET Example


<body>
<div id="result"></div>
<button onclick="sendAjaxRequest();">Send Request</button>
</body>
Explanation
In this example, the XHTML document contains an empty <div> with id
"result". When the Send Request button is clicked, the sendAjaxResult()
function is called.
The sendAjaxResult() function creates or re-uses a request object. The
request object is stored in a global variable. It is essential that we use a global
variable. Otherwise, there no way to know about the request object from the
onreadystatechange event handler (showResult). A GET request is then made
for the uri "city.html".
When the browser processes the request, every time there is a change in
state, system calls the showResult function. We are only interested in a
successful completion of the reply. In that case, we display the responseText
property of the request in the "result" div element.

(C) Web Age Solutions Inc. 2010

4-12

WA1503 Comprehensive AJAX

Making a POST Request

POST method should be used when large


amounts of data needs to be sent.
Take these steps to send a POST request:

Use "POST" as the method type in the open()


function call.
Set the Content-Type request header to
"application/x-www-form-urlencoded;
charset=UTF-8".
Supply the name value pair of the form element
input in the send() method call.

The values should be URL encoded using the escape()


function. For example, ">" will be replaced by "%3E".

Example
In this example, we submit a login form using a POST request. There are two
text boxes with ID "user" and "password". We retrieve their values (text
entered by the user) and form the request body. We also make sure that the
encoding of the Content-Type header is set to UTF-8. System always encodes
the request body text using this encoding. The correct content type will pass
on the encoding information to the server that can then correctly process the
request.
function sendAjaxRequest() {
request = createRequest();
var user = document.getElementById("user").value;
var password = document.getElementById("password").value;
var body = "user=" + escape(user) + "&password=" + escape(password);
request.onreadystatechange = showResult;
var url = "LoginServlet";
request.open("POST", url, true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
request.send(body);
} Solutions Inc. 2010
(C) Web Age

4-13

WA1503 Comprehensive AJAX

Making Concurrent Requests

A key problem with the AJAX API is that the


onreadystatechange event handler method does not receive any
reference to the request object.

This makes it difficult for the event handler method to get the
request object for which the method is being invoked.

A simple solution is to declare a global variable for the request.

The problem with the global variable approach is that, we can


not issue multiple simultaneous requests.

See the pattern below.

For example, say, the user interacts with the application which
causes a request to be sent. While the user is waiting for that
result, she does something else, for which another request needs
to be sent. Now, the second request will cause the first one to be
aborted or cause other problems with race conditions.

The pattern with the global variable approach goes as follows.


var req; //The global variable
function sendRequest() {
req = createRequest();
req.onreadystatechange = displayResult;
req.open();
req.send();
}
//The event handler uses the global
//variable
function displayResult() {
var reply = req.responseText;
//
}
In this case, if sendRequest() is called a second time, while the reply for the first call is still
incomplete, the displayResult method will have problems with race condition. A race condition
occurs when two separate sequence of events work with the same variable.

(C) Web Age Solutions Inc. 2010

4-14

WA1503 Comprehensive AJAX

Making Concurrent Requests

A good solution to this problem is to build a simple framework that uses an inner function.
Example:

function ajaxGet(url, onLoad) {


var xhr = createRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status == 200) {
onLoad(xhr);
}
xhr = null; //Avoid IE memory leak
}
}
xhr.open("GET", url, true);
xhr.send("");
}

The ajaxGet function above takes two parameters:


1. url A GET request will be sent for this URL.
2. onLoad Reference to a function that will be called when the reply is completely and
successfully received. This function takes the request object as a parameter.
Here is how the ajaxGet() function may be used.
function doRequest() {
ajaxGet("response.txt", handleReply);
}
//This way, our event handler can receive
//the request object.
function handleReply(r) {
var div = document.getElementById("result");
div.innerHTML = r.responseText;
}
<button onclick="doRequest();">Make Requests</button>
<div id="result">Click on the button above to make a AJAX request.</div>

(C) Web Age Solutions Inc. 2010

4-15

WA1503 Comprehensive AJAX

Making Concurrent Requests

With concurrent request enabled, the same callback function


may get called for different requests:

The reply callback function needs to distinguish under what


context it is running.

For example a user may request to remove several items from the
shopping cart without waiting for the reply for each request.

For example, for each item successfully removed from the cart, the
callback may show a status message showing the name of the
product that was removed.

To solve this problem, we need to associate extra context data


to each AJAX request. This data needs to be passed to the
callback.
To solve this problem, we modify the ajaxGet function a little bit
as shown below.

function ajaxGet(url, onLoad, data) {


var xhr = createRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status == 200) {
onLoad(xhr, data);
}
xhr = null; //Avoid IE memory leak
data = null;
}
}
xhr.open("GET", url, true);
xhr.send("");
}
Example usage:
ajaxGet("RemoveItem", showStatus, product);
function showStatus(request, product) {
//Show the name of the product removed
}

(C) Web Age Solutions Inc. 2010

4-16

WA1503 Comprehensive AJAX

Memory Leak With Inner


Function

In the ajaxGet() method, the inner function is invoked by AJAX at a


later time after the ajaxGet() method has returned.
But the inner function refers to the variable xhr that has been defined
in the scope of the outer function ajaxGet.
For the inner function to work, system needs to preserve the variable
stack frame of the outer function.

Variables like xhr are created in the stack of the outer function.

ECMA script specification does not mention exactly when the stack of
the outer function will be destroyed to free up memory.
IE does not appear to destroy the stack at all. this leads to severe
memory leak.
To solve this problem, we explicitly set the variables of the outer
function to null when we are done using them. This solves the memory
leak problem.

We are done with the request object after the readyState changes to 4.

Always do stress test or endurance test of an AJAX application to make sure


that there are no memory leaks in the browser. Inner functions that are called
after the outer function has exited can lead to serious memory leaks in IE. This
problem does not exist in FireFox.

(C) Web Age Solutions Inc. 2010

4-17

WA1503 Comprehensive AJAX

A POST Utility Function


function ajaxPost(url, requestData, onLoad, data) {
var xhr = createRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
logger.trace("HTTP reply status: " + xhr.status);
if(xhr.status == 200) {
onLoad(xhr, data);
}
xhr = null; //Avoid IE memory leak
data = null;
}
}
var body = "";
for (var name in requestData) {
if (body.length > 0) {
body = body + "&";
}
body = body + escape(name) + "=" + escape(requestData[name]);
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(body);
}

The ajaxPost function is similar to ajaxGet, but, has a few notable differences.
The method allows concurrent requests. Also, The POST body data is sent as
the requestData object. An example on how to call this function will show you
how the requestData object is constructed.
var requestData = new Object();
requestData.orderId = "1000";
requestData.operation = "CANCEL";
ajaxPost("ManageOrderServlet", requestData, showStatus, null);
The example above will send a POST request for the ManageOrderServlet
URL. The request body will look like this:
orderId=1000&operation=CANCEL

(C) Web Age Solutions Inc. 2010

4-18

WA1503 Comprehensive AJAX

Mozilla XmlHttpRequest
Extensions

None of these extensions (for Mozilla and IE) are


currently covered by the W3C specification. Using
them can lead to a better application but tie the
application to a specific browser.
Properties:

onprogress an event handler function that is called to


inform progress of a HTTP request.
onerror an event handler function that is called if a HTTP
request ends in an error.
onload an event handler function that is called to when
the reply is successfully and completely received.

This can be used as a simpler alternative to the


onreadystatechange event handler. See other advantages
below.

The three event handlers mentioned above have a key distinction from the
onreadystatechange event handler. A function registered with the latter, as we
have already discussed, does not receive any parameters. For these three
events, the function will receive an event object. This is consistent with the
DOM event model. For example:
function sendRequest() {
var req = new XMLHttpRequest();
var req.onload = processReply;
//req.open and req.send omitted for brevity
}
function processReply(evt) {
//Locate the request object
var req = evt.target;
var reply = req.responseText;
//Do something with the reply
}

(C) Web Age Solutions Inc. 2010

4-19

WA1503 Comprehensive AJAX

Mozilla XmlHttpRequest
Extensions

Methods:

addEventListener (type , handlerFunction, useCapture)

This function behaves the same as way as the


addEventListener function of the Element DOM object. Here,
type can be "load", "error", etc.

dispatchEvent (evt) Fire an event that is created artificially


from JavaScript code.
removeEventListener (type , handlerFunction, useCapture)
Remove an event handler function that was registered
earlier.
overrideMimeType(mimeType) Causes the reply to be reinterpreted based on the supplied mimeType. For example,
if the original MIME type in the Content-Type reply header
was "text/html", we can call this function with the type
"application/xml".

The addEventListener method, as we know from the Advanced DOM API


chapter, allows us to register multiple event handlers. This may be useful for
complex applications.

(C) Web Age Solutions Inc. 2010

4-20

WA1503 Comprehensive AJAX

IE Microsoft.XMLHTTP
Extensions

Property:

responseBody An array of bytes containing the


raw reply data. Useful, when the reply is not
textual.

JavaScript can not deal with binary array data. Can be


used from VB.NET, C# etc only.

responseStream Returns an IStream interface


for the response body. Useful when the client
wants to load data directly without replying on the
request object.

(C) Web Age Solutions Inc. 2010

Once again, not usable by JavaScript.

4-21

WA1503 Comprehensive AJAX

Ajax Caching

By default both Mozilla and IE caches all GET


requests. See notes below on how long a cache stays
current.
POST requests are never cached by the browser.
If an Ajax GET request is made for an URL that is
already in cache, the readyState property of the
XMLHttpRequest object goes through the usual life
cycle values. The browser does not do any network
communication with the server. Finally, when
readyState is 4, browser sets the responseText
property to the value from the cache.

This way, the application code does not have to know if the
reply data came from the cache or the network.

How long is a URL cached by default?


IE caches all Ajax GET requests made from a page for the life time of the
page. Even if you refresh the page, the caches are not recreated. Mozilla will
delete the caches if you refresh the application's page. Also, Mozilla seems to
destroy the cache when the keep alive connection to the server is closed after
a period of time. In short, it is more likely in Mozilla that a GET request cache
will be deleted and recreated.
You can change this default cache duration. We will discuss that next.

(C) Web Age Solutions Inc. 2010

4-22

WA1503 Comprehensive AJAX

Control Cache Duration

The server side code can use the Expires or the Cache-Control reply
header to control the duration of the cache in the browser.

To disable caching of a GET request, do one of the following:

Cache-Control, introduced in HTTP 1.1, provides much more flexibility.


Generally, speaking use Cache-Control.
Set the Expires header value to 0. Indicating, the cache should be
destroyed right away. Or,
Set the Cache-Control header value to no-cache.

To set a time limit for the cache of a GET request, do one of the
following:

Set the Expires header to the expiration date and time in this format: Wed,
13 Feb 2008 16:00:00 GMT. Or,
Set the maximum age of the cache in seconds by setting the Cache-Control
header's max-age property. For example, a value of max-age=30 will
cause the browser to use the cache for 30 seconds only.

Time zone for the Expires header must be in GMT.


Example HTTP reply header where caching is disabled:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: no-cache
Content-Type: text/plain
Content-Length: 28
Date: Wed, 13 Feb 2008 13:27:02 GMT

(C) Web Age Solutions Inc. 2010

4-23

WA1503 Comprehensive AJAX

Advanced Cache Control

The previous techniques either disable cache or set a fixed expiry for the cache.
Alternatively, the Last-Modified reply and If-Modified-Since request headers can be
used to perform more dynamic cache invalidation. See use case below.

When the data is first fetched using a GET request, the reply should contain two
headers:

In this scheme browser based caching is disabled and every GET request is sent to the server.
The server decides if data has changed since the last reply. A reply document is sent only if
data has changed. This saves unnecessary database access and reduces the size of the reply
document.

Cache-Control is set to max-age=1 to set a low cache age and effectively disable cache.
Last-Modified is set to the time when the reply data (such as product information) was last
modified in the database.

The reply from this first request for the URL is cached by the browser. Even though,
max-age is only 1 second, the cached data may be used as we will see next.
When a GET request is made for the same URL again, the browser behaves as follows:

The If-Modified-Since request header is set to the value of the Last-Modified header from the
cached reply. JavaScript application code doesn't have to do anything.
The server side code should inspect the value of the If-Modified-Since header. If the database
data has not changed since that time, it should reply with a 304 status code and an empty
body. This avoids expensive database access and reduces HTTP network traffic.
When the browser sees a 304 reply code, it fetches the reply data from the cache. The
responseText property of the XMLHttpRequest object is set to that data.

Let us say that you are sending a request for a URL that returns product information. This
information can be cached by the browser as long as the product data has not changed in the
server. This feature is difficult to implement using the Cache-Control reply header alone since
we have no idea when the product data will be modified.
Example headers for first reply to a GET request:
HTTP/1.1 200 OK
Last-Modified: Wed, 13 Feb 2008 13:49:17 GMT
Cache-Control: max-age=1
Content-Type: text/plain
Content-Length: 28
A subsequent GET request will look like this:
GET /AjaxWeb/GetProductData?id=1 HTTP/1.1
Host: nero:8080
If-Modified-Since: Wed, 13 Feb 2008 13:49:17 GMT
Server can return with a 304 status code and an empty body:
HTTP/1.1 304 Not Modified
Server: Apache-Coyote/1.1

(C) Web Age Solutions Inc. 2010

4-24

WA1503 Comprehensive AJAX

Review Questions
1.

2.

3.

4.

5.

T/F: There are many different implementations of


the request object.
What is the onreadystatechange property of the
request object used for?
What readyState and status do you want to
check for before processing the response?
What is the difference between the responseText
and responseXML properties?
What 2 methods do you need to invoke on the
request object to interact with a server using AJAX?

(C) Web Age Solutions Inc. 2010

4-25

WA1503 Comprehensive AJAX

Review Questions
6.

7.
8.
9.

10.

T/F: You should attach headers to the request after


invoking the open and send methods.
When should a POST be used instead of a GET?
What must also be sent when sending a POST?
What is a solution for dealing with the concurrent
request problem?
How can you prevent memory leaks in IE when
dealing with concurrent requests?

(C) Web Age Solutions Inc. 2010

4-26

WA1503 Comprehensive AJAX

Review Answers
1.
2.

3.

4.

5.

True
The onreadystatechange property is used to
specify the event handler (i.e., JavaScript function)
that is invoked at various times after the request is
sent.
readyState should be 4 and status should be
200.
responseText simply corresponds with the text
contained inside the reply body and can contain
markup. responseXML is a DOM document
representing the reply body.
open and send

(C) Web Age Solutions Inc. 2010

4-27

WA1503 Comprehensive AJAX

Review Answers
6.

7.

8.
9.

10.

False. You do it after calling open, but before calling


send.
POST should be used instead of GET when sending
large amounts of data.
A request body that is URL encoded
The onreadystatechange event handler should
be defined as an inner function to an outer function
that creates the request object and sends the
request. It should pass the request object to a
function that updates the page after the reply has
been successfully and completely received.
Set the request and context data variables of the
outer function to null when you're done using them.

(C) Web Age Solutions Inc. 2010

4-28

WA1503 Comprehensive AJAX

WA1503 Comprehensive AJAX


CSS2

(C) Web Age Solutions Inc. 2010

5-1

WA1503 Comprehensive AJAX

Objectives

At the end of this chapter, participants will be able


to:

Understand the CSS2 technology


Understand the need for CSS2
Discover the different value types
Know how to define style sheet rules
Discover various ways selectors may be coded
Understand the Visual Formatting model
Know how to position content using normal, relative and
absolute positioning
Learn properties applicable to color, background and font

(C) Web Age Solutions Inc. 2010

5-2

WA1503 Comprehensive AJAX

Introduction

CSS2 (Cascading Style Sheet Level 2) was introduced by the World


Wide Web Consortium in 1998.
CSS Level 1 had been introduced two years earlier.

CSS1 added publishing attributes such as color to HTML documents.


Certain elements (e.g. <font>) were no longer needed.
CSS1 presented consist "look and feel" techniques.

The CSS2 specification is:


http://www.w3.org/TR/REC-CSS2/Overview.html.
CSS2 enhancements:

More pseudo-classes introduced.


Media enhancements made their debut.
Greater flexibility with selectors.
Positioning schemes enhanced with stacking.
Industry support.

CSS1 was introduced by the W3C in 1996 as the Cascading Style Sheet Level
1 specification. The general idea was to reduce the dependency of HTML
documents on granular elements for visual formatting while adding capabilities
that HTML simply didn't possess (e.g. color).

(C) Web Age Solutions Inc. 2010

5-3
3

WA1503 Comprehensive AJAX

New in CSS2

One of the biggest changes in CSS level 2 is the wide


range of selectors.
Tag attributes can be specified using bracket ( [ ] )
notation.
Multiple class names can be specified for an element.
The any child selector ( > ) applies the style to any
child element of the specified element.
The asterisk functions as a "wildcard" selector,
matching any element.

The W3C recognized with the growing popularity of the Web selectivity was a
challenge of major importance. The choice of selectors in CSS Level 2 is very
impressive.
The asterisk has the widest influence on the document tree. For example, this
specification sets the margin of all boxes to 3 centimeters:
* { margin: 3cm; }

(C) Web Age Solutions Inc. 2010

5-4

WA1503 Comprehensive AJAX

New in CSS2

New values for display property:

run-in
compact

New i18n values for list-style-type.


inherit value that explicitly states a property
should be inherited from the ancestor.
New pseudo-classes such as :hover and
:focus.
Three-axis positioning with "z-index".

Run-in and compact join the list of boxes from CSS1: block, inline and none.
Property value inheritance is not new, but now can be explicitly requested
using inherit. This is of course the default.

(C) Web Age Solutions Inc. 2010

5-5

WA1503 Comprehensive AJAX

Simple Example

Before going any deeper, let's look at a simple


example.
Consider the following HTML:
<html>
<head>
<link rel="stylesheet" type="text/css"
href="CSSSimpleExample.css" />
</head>
<body><h1>Heading 1</h1>
<p>This is a paragraph</p>
<p class="important">This is important!</p>
</body>
</html>

Note the <link> tag; this directs the browser to apply the external style sheet to
the document. Here is the entire style sheet:
/* Simple CSS */
h1 { font-family: Copperplate Gothic Light; color: blue}
.important { font-family: Bookman Old Style; font-size: 12pt;
font-size: 12pt; color: red; text-decoration: underline;}
This is a simple text file. We will study alternative ways of styling on later
slides.

(C) Web Age Solutions Inc. 2010

5-6

WA1503 Comprehensive AJAX

Formatted Output

Output on the browser:

The heading is colorized and the paragraphs


are rendered differently.

The <h1> rendering reflects the rule imposed by the style sheet. The second
paragraph is dramatically different from the first paragraph in presentation. To
attempt this rendering with HTML elements would be cumbersome, and would
require that several additional tags be hard-coded in the HTML source.

(C) Web Age Solutions Inc. 2010

5-7

WA1503 Comprehensive AJAX

Unformatted Output

If we remove the <link> tag:

This is rendering that the browser generates by


default; black font and each paragraph is displayed
with identical formatting.

Now the styling is absent and the browser uses default rendering. Notice that
the text in the second paragraph is rendered identically to first paragraph. The
relative important of paragraph two is not as obvious as it was on the previous
slide.

(C) Web Age Solutions Inc. 2010

5-8
8

WA1503 Comprehensive AJAX

Basic Syntax

A style sheet consists of one or more styling rules.


Each rule consists of a selector and declaration block

A selector is a filter that determines the XHTML elements


where the styling rule is applied; e.g.
h1 Apply the rule to all h1 elements.
A declaration block consists of a collection of style property
and value; e.g.
{ color: red; font-family: Times New Roman; }

You may also comment your style sheet using /* and


*/:

Comments can be placed anywhere in the style sheet.


Example:
/* This is a comment */

Complete example of the rule shown above:


h1 {color: red; font-family: Times New Roman;}
Note the following aspects of the syntax:
1. Selector is separated from the declaration block using white space.
2. The entire declaration block is encapsulated within {}.
3. Style property is separated from the value using ":".
4. A property/value pair is separated from the next one using a ";". It is
optional to provide a ";" for the last property.
CSS2 offers more flexibility with selectors than was available with CSS1. You
can define fairly complicated filters to decide which elements will be eligible
for the rule.

(C) Web Age Solutions Inc. 2010

5-9
9

WA1503 Comprehensive AJAX

Creating a Style Sheet


A style sheet can be created in separate file as an external style sheet or can be
coded in the HTML file. When created in a separate file, use the customary
extension of .css.

Use an external style sheet from an HTML file using the <link> element.
<head>
<link rel="stylesheet" type="text/css" href="CSSSimpleExample.css" />
</head>

When coded in the HTML file, use the style element or the style attribute (or)
both.

In the <head> section, code the <style> tag:


<style>
p { font-size: 12 pt;}
</style>
Use of "inline" styles is also supported:
<p style="font-size: 12 pt;"> . . .

You can import an external style sheet using the @import directive. Example:
@import "HoverStyles.css"

The @import must be coded before the first rule in the style sheet.

This directive must be included in the <style> tag scope if coded in the HTML
document.

Use of external style sheets is beneficial because an arbitrary number of HTML documents
may link to that file. An HTML document can link to an arbitrary number of style sheets.
Inline styles override any styles listed in the <head> section. Any styles listed in the <head>
section override any styles available in an external style sheet.

(C) Web Age Solutions Inc. 2010

5-10
10

WA1503 Comprehensive AJAX

Value Types

The value of a property can be length, color, time etc.


Length value type; used to specify width, height and font size of elements. The
unit is mandatory. There is no default unit in CSS2. Allowed units:

px - Pixels (1/72 in). e.g., {width: 12px; height: 10px}

cm - Centimeters

in - Inches

pt Points

em - Percentage of font size

ex - Percentage of the "x-height"

mm - Millimeters

pc - Picas (1pc = 12pt)


Percentage value type; percentage of a previous property value; e.g.
p {font-size: 24pt;}
p { line-height: 150%;}

Now the height of a line in the paragraph will be 150% taller than 24 points.
URL value type; used to locate images and other resources. e.g.:
body { background: url("images/leaves.jpg"); }

Value types are coded after the property, following the colon (:). Length value
types permit you to specify, for example, the font size in a variety of ways.
Consider the following where we display the paragraph text in letters 2
centimeters high:
<p style="font-size: 2cm;">This is BIG text!</p>
We can also use the more traditional points:
<p style="font-size: 12pt;">This is more normally-sized text!</p>

(C) Web Age Solutions Inc. 2010

5-11

WA1503 Comprehensive AJAX

Value Types

Color value types

Can specify using color name:


p { color: blue; }
Can specify using RGB (red-green-blue) value:
p { color: #0000ff; } /* blue */
p { color: rgb (0,0,255); } /* blue*/

Angle value type; can be expressed as degrees


(deg), grads (grad) or radians (rad).
Time value types; can be expressed in milliseconds
(ms) or seconds (s).
String value types; can be enclosed in single quotes
(') or double quotes (").

There are several predefined names that can be used for color; among them
aqua, black, blue, gray, green, olive, white, yellow (complete list follows on a
later slide). The RGB specification permits you to "compose" a color based on
relative amounts of red, green or blue. 0 (zero) indicates no contribution from
that color; 255 (ff in hexadecimal) indicates the maximum contribution.

(C) Web Age Solutions Inc. 2010

5-12
12

WA1503 Comprehensive AJAX

Selectors

Selectors are the core of the rule. A selector acts as a filter. System applies the
selector to find out which XHTML elements will be eligible for a styling rule.
At a broad level, there are two types of selectors:
Element identifier These selectors use an element's tag name, attribute or position
among its siblings in the DOM tree to filter the elements. For example, when the name
of an HTML element is used as a selector, the browser applies the rule to all such
HTML elements.

A pseudo-class. This type selector uses the dynamic state of an element to identify it.
For example, to underline a paragraph when the mouse pointer "hovers" over it:
p:hover { text-decoration: underline ;}
To change the color of a visited hyperlink to green:
a:visited { color: green; }

After the system applies the selectors, an XHTML element may be eligible for
multiple styling rules. Rule preference is:

inline style
embedded style sheet
external style sheet
If class and ID attributes are present, then ID wins because IDs are more specific than
classes. In XHTML, an ID attribute value must be unique. Similarly an attribute selector
(denoted by [] )is preferred over class.

Here is an example of how multiple rules can be applied to an element.


<style>
p {font-family: Arial; font-size: 10pt}
.fancy {font-size: 24pt} /* Class selector */
</style>
<body>
<p>Para 1</p>
<p class="fancy">Para 2</p>
</body>
Here, the second paragraph is eligible for both styling rules. It will be rendered
using Arial font with size 24pt.

(C) Web Age Solutions Inc. 2010

5-13

WA1503 Comprehensive AJAX

More on Selectors

The universal selector matches any element type.

This selector is designated by an asterisk (*).


For example, to apply a font family to all suitable elements
(<p>,<h1>, etc.):
* { font-family: Bookman Old Style; }

The type selector matches an element name.

Use the element name.


For example, to apply a font-family to <h3> elements:
h3 { font-family: Helvetica; }

The class selector creates a rule that an element occurrence


may reference using the class attribute.

Use a dot (.) as first character:


.warning { color: red; }
<p class="warning"> ... </p>

Optionally a type selector can immediately precede the class.

p.warning {color: red} /* This class can be used with p tag only */

The type selector will apply the rule to all element types, or tags, in the
document that are of that type.
The class selector is particularly powerful because the web page author can
selectively determine what tags should receive the indicated styling. Notice
that a dot must precede the class name when defined in the style sheet. Tags
that do not reference the class using the class attribute will not receive the
styling.

(C) Web Age Solutions Inc. 2010

14
5-14

WA1503 Comprehensive AJAX

More on Selectors

The ID selector matches any element type that has the associated id
attribute.

This rule applies to any tag that has an id="abc"


#abc { font-size: 24pt; }

The following will apply only to <p> tags that have an id="abc":
p#abc { font-size: 24pt; }

The child selector matches an element type that is immediately


descended from an element type.

The child is exactly one level lower on the document tree from the parent. Separate a
parent selector from child by ">".
For example, to apply a font-family to only <p> tags that are children of <div> tags:
div > p { font-family: Helvetica; }
#id1 > #id2 {...} //Select element with id id2, child of id1.

The descendent selector matches an element type that is contained by


element within its scope.

A descendent is any level lower than the parent. See details below. Separate parent
selector from a descendent by space.
For example, to apply a font-family to only <p> tags that are contained (descended
from) <div> tags:
div p { font-family: Helvetica; }

Imagine we have two lists;


<ol id="list1">Required books</ol>
<ol id="list2">Suggested Books</ol>
To style the lists individually we might code the following rules:
#list1 { color: red;}
#list2 { color: green;}
The advantage is we don't have to add/modify code in the HTML.
A child is a descendant, but a descendant is not necessarily a child. This
terminology reflects the reality of the document tree built in RAM by the
browser. Consider this example:
div > span {color: blue}
div span {color: red}
<div>Text1 <span>Text2 <span>Text3</span></span></div>
Here, the immediate child of <div> - Text2 will be shown in blue. Text3 is a
grand child of <div>. It is a descendent but not child. It will be shown in red.
(C) Web Age Solutions Inc. 2010

5-15

WA1503 Comprehensive AJAX

More on Selectors

The attribute selector matches an element that has the


specified attribute and optionally the specified value.

To match table elements that have a border attribute:


table[border] { font-family: Helvetica;}
To match table elements that have a border attribute set to 1:
table[border="1"] { font-family: Helvetica;}

Pseudo-class selectors draw on a system-defined class; they


are:

:first-child matches the first child of an element


:visited applies only to hyperlinks that have been visited (clicked)
:link - applies only to hyperlinks that have not been visited
:active applies only to hyperlinks when the link is clicked (very brief duration)
:hover applies to any element specified when the mouse pointer is placed over the
element
:focus applies to any element that has the focus

The :hover pseudo class is very popular. Consider the following HTML:
<p>Underline this paragraph when the pointer is rolls over it!</p>
To apply the desired underlining, code this rule
p:hover { text-decoration: underline ;}
Note that we used a "p" in front of the pseudo-class name. This targets the
element type to which the rollover effect applies.

(C) Web Age Solutions Inc. 2010

5-16
16

WA1503 Comprehensive AJAX

Grouping Elements

Oftentimes, you wish to apply the same rule to more than


one element type.
You may do this by using a comma to separate the element
types.
For example, to style <h1> <h3> and <div> with the
same font family:
h1, h3, div { font-family: Bookman Old Style }

Using this technique prevents you from coding the same


rule repeatedly.
You can chain child and descendent selectors:

#d1 > #d2 > #d3 {color: red} Selects d3 that is a grandchild of d1
#d1 #d2 #d3 {color: blue} d3 is a descendent of d2 which descends from d1.

The alternative is:


h1

{ font-family: Bookman Old Style; }

h3

{ font-family: Bookman Old Style; }

div

{ font-family: Bookman Old Style; }

This technique requires redundant code; grouping these elements as shown


on the slide reduces the coding effort.

(C) Web Age Solutions Inc. 2010

17
5-17

WA1503 Comprehensive AJAX

The Box Model

The W3C proposes that the box model be used to generate


rectangular boxes around elements. The boxes are to be laid
out according to the Visual Formatting Model (discussed later).
The box model defines a box as a rectangle with dimensions for

Margin this is the area separating the box from neighboring


content and is transparent
Padding the area between the margin and the content
Border a line (solid, dashed, dotted, etc.) between the margin
and the padding
Content the content of the box

You have a fine degree of control over the various properties of


these area types; we will look at some examples on the
following slides to give an idea of the richness of the box model.

(C) Web Age Solutions Inc. 2010

5-18
18

WA1503 Comprehensive AJAX

Box Model Example

Consider this rendering:

This is a box that contains a <div> and a <p> tag.

The <div> border style is groove.


The <p> border style is dashed.
The rules are shown in the notes.

Here are the rules used to generate the box that is displayed on the slide:
div {background: green;
margin: 20px 30px 20px 30px; /* top right bottom left */
padding: 20px 30px 20px 30px; /* top right bottom left */
border-style: groove; border-width: thick; border-color: blue;}
p { background: gray;
margin: 10px 15px 10px 15px; /* top right bottom left */
padding: 50px 60px 50px 60px; /* top right bottom left */
border-style: dotted; border-width: medium; border-color: blue;}

(C) Web Age Solutions Inc. 2010

5-19

WA1503 Comprehensive AJAX

Box Properties

The preceding example gave an idea of the richness of the box model.
Margin area can be controlled by specifying length values for top, right, bottom
and left.
Padding area can also be controlled as above.
You can specify each dimension with shorthand or with individual properties.

Shorthand:
margin: 20px 30px 20px 30px; /* top right bottom left */

Individual properties:
margin-top: 20px;
30px;

margin-right: 30px; margin-bottom: 20px margin-left:

Padding supports similar properties (e.g. padding-top).

Many border types are supported; the following is a sampler of values supported
by the the border-style property:

dotted
dashed
solid
double
groove

Color properties are also supported for border color:


border-top-color, border-right-color, border-bottom-color, border-left-color
The shorthand technique allows you to list values for margin and padding as
stated on the slide. Border width is also eligible for shorthand. Therefore
margin, padding and border are really shorthand properties. Defaults are
applied whether dealing with margins, padding or borders. For example:
border-top-width: thin
Is the same as:
border-width: thin thin thin thin
Furthermore, this is identical to:
border-top-width: thin; border-right-width: thin; border-bottom-width: thin;
border-left-width: thin;

(C) Web Age Solutions Inc. 2010

5-20

WA1503 Comprehensive AJAX

The Visual Formatting Model

The Visual Formatting Model specifies that each element in the


document tree generates 0 or more boxes according to the box model
The layout of a box is controlled by:

Box dimensions and type


Positioning scheme
Relationship between elements
External factors (e.g. resizing the browser window on the desktop)

A containing block is a block of screen area that holds the descendants


of an element.

Descendant boxes are displayed in the containing block.


Simple example:
<div> <! establishes containing block for -->
Div text
<p>Paragraph text</p> <! p box -->
</div>

The <div> tag has inline content ("Div Text") and block content (the <p>
tag).

One more observation on this example:


<div>Div text
<p>Paragraph text</p>
</div>
As indicated on the slide, "Div Text" is inline content. For convenience, this
content is also associated with an anonymous block box. In conclusion, we
have three boxes: The <div> box, the <p> box and an anonymous block box.

(C) Web Age Solutions Inc. 2010

5-21
21

WA1503 Comprehensive AJAX

Types of Boxes

Block box wrapper for content of a block element (e.g. <div>,<p>).


<div> <! div block box -->
Div text
<p>Paragraph text</p> <! p block box -->
</div>

Anonymous block box any inline content of a containing block box is


wrapped into an anonymous block box if descendants in turn generate
block boxes.
<div> <! div block box -->
Div text <! forced into anonymous block box -->
<p>Paragraph text</p> <! p block box -->
</div>

Inline box wrapper for content of non-block element (e.g.


<em>,<span>).
<p>This is<span>text contained in inline box</span></p>

Anonymous inline box wrapper for content of a containing block box


is wrapped into an anonymous block box if descendants in turn
generate only inline boxes

For the last bullet, consider again this HTML fragment:

<p>This is<span>text contained in inline


box</span></p>
The text "This is" is placed in an anonymous
inline box. Why not an anonymous block box?
Because the contained tag, <span> is inline by
default. We could change that behavior as we
will see on a future slide.

(C) Web Age Solutions Inc. 2010

5-22
22

WA1503 Comprehensive AJAX

Types of Boxes

Compact box formatted like a one-line inline box if followed by


a block box and if the margin of the block box is large enough
to contain the compact box.

This type of box can be requested using display property of


'compact'.
A compact box will not be used if side margin of adjacent block box
is too small.

Run-in box if followed by a block box, this box becomes the


first inline box of the block box.
Useful when a heading should be merged with a paragraph.
This type of box can be requested using display property of
'runin'.
For example:
h2 { display: run-in; }
. . .
<h2>HTML was created</h2><p>for interchange of documents.</p>

The run-in example would produce the following output


HTML was created for interchange of documents.
Without the display specification of run-in the output would be:
HTML was created
for interchange of documents.

(C) Web Age Solutions Inc. 2010

5-23

WA1503 Comprehensive AJAX

Display Property

The display property specifies what box type will be generated for an HTML
element.

span { display: block; }


Other tags that have inline display by default are <font> and <em>

The most common values for display:

You can request a different box type by including this property in your style sheet.
For example, a <span> tag has inline formatting by default-to change this behavior to
block:

block
run-in
inline
compact

We can change the behavior of a block element quite readily:

p { display : inline; }
...
<p>This is not </p>
<p>the usual paragraph behavior!</p>
Displays:

We can also have some fun with <span>!


Consider the follow HTML
span { display: block; }
...
<p>The spanned text<span>will appear on its own line.<span> How about
that?!</p>
The <span> tag has lost its default inline box behavior.

(C) Web Age Solutions Inc. 2010

5-24

WA1503 Comprehensive AJAX

Positioning Schemes

In CSS2 a box can be laid out according to one of three positioning


schemes:

Normal flow

Floats

First, box is laid out according to normal flow


Then box is taken out of the flow and shifted left or right as far as possible

Absolute

Block formatting of block boxes


Inline formatting of inline boxes
Relative positioning of block and inline boxes

Box is taken out of normal flow entirely


Then box is assigned a position

Position and float properties determine which positioning scheme will


be used.

By default, the browser will use normal flow and boxes will be laid out
according to block and inline guidelines. Properties such as "top" and "left" will
be ignored.

(C) Web Age Solutions Inc. 2010

5-25

WA1503 Comprehensive AJAX

The Position Property

Use the position property to request a positioning


scheme.
Typical Values:

static normal box positioned according to normal flow


(default).
relative the box is laid out according to normal flow and
then positioned relative to the containing block.
absolute the box is taken out of normal flow and then
positioned with respect to the containing block.

You can apply the position property to any element.


An element is 'positioned' if its position property is
specified as a value other than 'static'.

The positioning scheme is requested on the elements that will be affected. For
example, we may wish to relatively position spans within a paragraph:
span { position: relative; display: block; line-height: 12pt; font-size: 12pt; }
span.shiftedRight {top: 0pt; left: 120pt;}
span.shiftedUp {bottom: 12pt; left: 240pt;}
...
<p>Paragraph block
<span>Block box 1</span>
<span class="shiftedRight">Block box 2</span>
<span class="shiftedUp">Block box 3</span>
</p>
The positioning scheme if the containing block (in this case a <p> block) is not
relevant.

(C) Web Age Solutions Inc. 2010

5-26
26

WA1503 Comprehensive AJAX

Relative Positioning

To request relative positioning:

Relative positioning means that once a box has been laid out (in
its containing block), its position will be shifted relative to where
it would have been placed if relative had not been requested in
the first place.
The shifted amount can specified as:

anyelement { position: relative; }

top offset of top edge of box below top of containing block.


right offset of right edge of box to the left of right edge of
containing block.
bottom offset of bottom edge of box above the bottom of the
containing block.
left offset of left edge of box to the right of left edge of
containing block.

Let's consider the example from the previous notes. If the class attributes
where removed, the output would look like:
Paragraph block
Block box 1
Block box 2
Block box 3
which of course is customary. But if the styling in the previous notes is
applied, the output is dramatically different:
Paragraph block
Block box 1
Block box 3
Block box 2

(C) Web Age Solutions Inc. 2010

5-27

WA1503 Comprehensive AJAX

The Float Property

A float is a box that is shifted to left or right of the current


line.
Therefore, the box can "float" in either direction (left, right or
none).
Text flows to the left or right of the floating box (unless
prohibited by the clear property, discussed on the next slide).
For example:
<p><img src="images/Leaves Bkgrd.jpg" style="float: left; margin:
10px;"></img>This is text that can be flowed to the left or to the right of
the floating img. Select float: right to float the image to the
right;choose float: left to float the image to the left.</p>

If the style attribute is omitted in the example on the slide, then the text will be
placed to the right of the image and on the last line.
Notice that a margin property is present; this is important so that the text is
separated from the image edge and hence is more readable.

(C) Web Age Solutions Inc. 2010

5-28
28

WA1503 Comprehensive AJAX

The Clear Property

The clear property states which side (left, right or


both) may not be adjacent to (and therefore must be
clear of) an earlier floating box.
For example:
<p style="clear: left;">Left edge must be clear of floating
box. </p>

If the example is altered:


<p style="clear: right;">Left edge must be clear of floating box. </p>
Then the text will appear adjacent to the floating box. This is because now the left edge is permitted to be
adjacent to the floating box and the right edge must be clear of any earlier floating box.

(C) Web Age Solutions Inc. 2010

5-29

WA1503 Comprehensive AJAX

Absolute Positioning

Absolute positioning explicitly offsets an element type


with respect to its containing block.
Later sibling element types are not affected; i.e. the
absolutely positioned element is taken out of normal
flow.
The containing block is established by the nearest
positioned ancestor or if none exists the document
root.
The following specifies absolute positioning for
<span> tags:
span { position: absolute; }

Earlier we saw this example (we have now added the absolute value for span
positioning and relative for paragraph positioning):
p { position: relative; }
span { position: absolute; display: block; line-height: 12pt; font-size: 12pt; }
span.shiftedLeft {top: 0pt; left: 120pt;}
span.shiftedUp {bottom: 12pt; left: 240pt;}
The <p> tag is the positioned ancestor. The HTML markup remains
unchanged. The output is:

Block box 3
Paragraph block

Block box 2

Block box 1

(C) Web Age Solutions Inc. 2010

5-30

WA1503 Comprehensive AJAX

Layered Presentation

CSS2 introduces a three-dimensional axis for positioning of


boxes.

The "z-index" property can be used to specify a stack level.


A box always belongs to one stacking context but may start a local stacking context.
A stack level of 0 is generated for a box unless the z-index property is coded.
The element with the greatest stack level in a stacking context overlays other elements
at that position.

For example:
span.location { top: .5in; left: .5in;}
...
<span class="location" style="z-index: 1">Block box 1</span>
<span class="location">Block box 2</span>

If the z-index property were not coded, then the text "Black box 2" would
appear.
To enhance the example, we used:
span { position: absolute; border-style: groove; border-width: thin;
background-color: white; }
Otherwise each box is transparent and the rendering may not be desirable.
The background-color property is discussed later.

(C) Web Age Solutions Inc. 2010

5-31

WA1503 Comprehensive AJAX

Color Property

To specify foreground color, use the color property.


Color can be specified using predefined names:
aqua, black, blue
fuchsia, gray, green, lime
maroon, navy, olive
purple, red, silver
teal, white, yellow
Color can be also be specified using RGB (red, green,
blue) numbers as discussed on an earlier slide.
For example, to indicate silver text in a paragraph:
p { color: silver; }

Recall the earlier discussion on RGB when color value types were presented:
p { color: #0000ff; } /* blue */
p { color: rgb (0,0,255); } /* blue*/

(C) Web Age Solutions Inc. 2010

5-32

WA1503 Comprehensive AJAX

Background Properties

Background properties define values for the


background of a box's content and padding.
Background properties are not inherited but the
parent's background is visible because of the default
value of 'transparent' for background-color.
Background properties include:

background-color
background-image
background

For example, to set the background-image to a


graphics file:
p { background-image: nature.gif; }

Background color and images are quite popular on web pages.


The background property is a shorthand that can be used to set all properties.
Here we use it to set the background image:
body { background: url("images/nature.gif"); }

(C) Web Age Solutions Inc. 2010

5-33

WA1503 Comprehensive AJAX

Font Properties
As of HTML 4.0 strict, <font> was obsolete; font properties are
to be used instead. Common properties are presented here.
font-family Sans Serif, Helvetica, Bookman Old Style, etc.

font-size specified as percentage, absolute or physical size


(see length values earlier in chapter).

Relative can expressed as percentage:


p { font-size: 125%; }
Absolute size can be expressed as xx-small, x-small, small, medium, large, x-large,
xx-large.

font-style normal, italic, oblique


p{ font-style: italic; }

font-weight normal, lighter, bold, bolder

This example specifies bold:


p { font-weight: bold; }
The font weight is actually represented by an integer, 100 through 900 in increments
of 100. Normal is 400 and bold is 700. The preceding could also be specified as:
p { font-weight: 700; }

The cascading effect of CSS2 can be practically demonstrated with these


useful properties. For example, consider this style sheet snippet:
div { font-family: Bookman Old Style; }
p.sensitive { font-style: italic; }
span.critical { font-weight: bold; }
Here is the markup:
<div>This information in this document is propriety.<p
class="sensitive">Confidential policies are discussed. Only persons with the
<scan class="critical">necessary security clearance</scan>
are permitted access to the information herein.</span></p></div>
The text "necessary security clearance" is marked up as Bookman Old Style,
italic and bold.

(C) Web Age Solutions Inc. 2010

5-34

WA1503 Comprehensive AJAX

Summary

CSS2 is a significant improvement over CSS1.


A variety of value types is supported.
A wide range of selectors is available.
The page author has control over the
positioning of content using normal, relative
and absolute positioning schemes.
Boxes are laid out on a three-dimensional
axis.
Color, font and background properties can be
specified.

(C) Web Age Solutions Inc. 2010

5-35

WA1503 Comprehensive AJAX


Advanced DOM

(C) Web Age Solutions Inc. 2010

6-1

Event Handling

Elements in a document can fire events.

For example, clicking on a <button> element causes the onclick


event to be fired.

An event is represented by an Event object.

One or more event handler functions can be registered to


handle an event.

The Event interface is specified by W3C as a part of the DOM API.

When the event is fired, the browser invokes these methods


automatically.

Most elements can fire a predefined set of events (such as


onclick and onblur).

You can create custom event types and fire them using the DOM
API.

(C) Web Age Solutions Inc. 2010

6-2

The Event Object

Represents an event that will be or has been fired.


For default set of events, the browser takes care of creating
them and initializing them.

When an event handler method is invoked by the system, the


event object is passed to it as the first argument.

You can also, create a new event object by calling the


createEvent() method of the document object.

You can access various properties of the event to learn more


details (such as, for a mouse click event, the coordinate of the
point where the user had clicked the mouse).

An event object goes through this life cycle:

Created
Initialized Various properties are set.
Dispatched The event is fired
Handled Event handlers are called.

so far, you may have written event handler functions without knowing anything
about the Event object. In the next couple of slides we will learn about it in
details so that we can make our event handlers more powerful.

(C) Web Age Solutions Inc. 2010

6-3
3

The Event Object

Key properties:

type The name of the event. Such as "click" for the onclick event.
altKey, shiftKey, ctrlKey If Alt, Shift or Control key was pressed when the
event took place.
clientX, clientY The coordinate of the point where the event took place
relative rto the content area of the page.
screenX, screenY The same but relative to the top left corner of the
desktop.
timestamp Time when the event took place.
target (Mozilla), srcElement (IE) The original element that fired the event.
currentTarget (Mozilla only) The element where the event handler is
registered.
bubbles If true, if a child element fires an event, it will cause event
handlers associated with the parent elements to be also called. Mozilla only.
button the mouse button clicked. See details below.
keyCode (IE)/which (Mozilla) The UNICODE integer ID of the key pressed.

The button Property


0 for standard 'click', usually left button
1 for middle button, usually wheel-click
2 for right button, usually right-click
Difference between target and currentTarget
Let us say that a table row (<tr> element) contains a cell (<td> element). The
onclick event handler is registered for the <tr> element. If the user clicks on
the cell (the <td> element), the actual source of the event is the cell. As a
result, the target will be the <td> element. However, the event handler is
registered for the row (<tr> element). When this event handler is called, the
currentTarget of the event will be set to the row element.
Currently, there is no equivalent to the currentTarget property in IE.

(C) Web Age Solutions Inc. 2010

6-4
4

The Event Object

Key methods:

initEvent, initMouseEvent Used to initialize an


event. Discussed later. Mozilla only.
preventDefault() Prevents the default outcome
of the event without stopping firing of the
remaining event handlers. The event must be
cancelable. See details below. Mozilla only.
stopPropagation() Stops bubbling of events.
Mozilla only. In IE, set the cancelBubble
property to true to stop bubbling. Event bubbling
is discussed later.

The prevetDefault() function works as follows. Let us say that a user clicked on
a hyper link. By default, the browser will first call all the onclick event handlers.
Then it will proceed to load the document pointed to by the hyperlink. If from
an event handler function, we call the preventDefault() function for the event
object, system will continue to execute the remaining event handlers (if any).
But, it will not load the document pointed to by the hyper link.
The preventDefault() function works only for events that are cancelable. An
event is flagged at cancelable when it is first initialized. We will discuss event
initialization later. In Mozilla, the event type supports a cancelable property
that indicates if an event can be canceled. Example:
//This will work in Mozila only
if (theEvent.cancelable) {
theEvent.preventDefault();
}

(C) Web Age Solutions Inc. 2010

5
6-5

DOM Hierarchy

Event Bubbling

<table onclick="func2();">
Element
<tr onclick="func1();"> Element

<td> Element

In this example, a table element contains a row element (<tr>) which contains
a cell element (<td>).
The function func1() is registered as the onclick event handler for the row. The
function func2() is registered as the event handler for the whole table.
If a user clicks on the cell, system will go up the chain of hierarchy and call
each element's onclick event handler. In this case, the cell does not have an
event handler. So, nothing is done with the cell. System proceeds to call
func1() and then func2(). This behavior is called bubbling. Not all events
bubble up the chain. When you create your own event object, you can disable
bubble (even for events such as onclick that would otherwise bubble).

(C) Web Age Solutions Inc. 2010

6-6
6

Creating and Initializing an


Event

To create an event use:

To initialize an event object, for Mozilla, use a type specific


method of the Event interface.

Mozilla: document.createEvent(type) Returns a new event object


of a certain type. Common event types: "MouseEvent",
"KeyboardEvent" and "Event".
IE: document.createEventObject() Returns a new event object.

For all event types initEvent(name, bubbles, cancelable) See


details of each parameter below.
For "MouseEvent" type initMouseEvent(name, bubbles,
cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey,
altKey, shiftKey, metaKey, button, relatedTarget)

To initialize an event in IE, set various properties of the event


object (such as screenX, screenY etc.) after creating it.

Creation and initialization of events is only required if you are writing code to
fire events. Normally, a browser will take care of these things. Only advanced
programs need to fire event artificially.
Parameters of Event Initialization Functions
name Indicates the type of event. These names are usually same as the
event handler properties with the "on" prefix removed. For example, "click",
"mousedown", "change" and "load".
bubbles If true, all event handlers for the element that fired the event as well
as it's ancestors in the DOM tree will be invoked. For example, if a <div>
element contains a <p> element and the <p> element fires an event, the
handler for the <div> element will also be invoked.
cancelable If an event is cancellable, then an event handler method can
cancel further firing of the remaining event handlers.
view Pass the window object here.
detail - the Event's mouse click count.
screenX, screenY, clientX, clientY Discussed in the event properties section.
ctrlKey, altKey, shiftKey, metaKey, button Discussed in event properties
section. The metaKey property applies to MAC machines only, where there is
a meta key.
relatedTarget When the mouse leaves an element and enters another one,
an onmouseout event is fired for the first element. The second element is set
as the related target.
(C) Web Age Solutions Inc. 2010

6-7
7

Dispatching an Event

DOM allows you to artificially fire an event


without the user doing anything.
In Mozilla, call the dispatchEvent for the
element that is firing the event.

element.dispatchEvent(event)

In IE, call the fireEvent method for the


element that is firing the event.

element.fireEvent(name, event)
name The type of event. Such as "onclick",
"onload".

Normally an event is fired after a user interacts with an element, such as click
on a button. DOM allows a program to fire an event programmatically without
any user interaction.

(C) Web Age Solutions Inc. 2010

6-8

Example
function mimicEventMozilla() {
var b2 = document.getElementById("b2");
var evt = document.createEvent("MouseEvent");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
b2.dispatchEvent(evt);
}
function mimicEventIE() {
var b2 = document.getElementById("b2");
var evt = document.createEventObject();
evt.screenX = 10; evt.screenY = 20; //Initialize
b2.fireEvent("onclick", evt);
}

The example above shows how to create, initialize and fire events, depending
on the browser. In both cases, we fire the clicked event for a button with id
"b2". If that button has an onclick event handler, such as below, it will be
invoked.
<button id="b1" onclick="b1Clicked();">Button One</button> <br/>
<button id="b2" onclick="b2Clicked();">Button Two</button>
The b1Clicked() and b2Clicked() functions can be written like this:
function b1Clicked() {
try {
mimicEventIE();
} catch(e) {
mimicEventMozilla();
}
}
function b2Clicked() {
alert("Handled event in b2");
}
No matter which button you click, the b2Clicked() function will be eventually
called.

(C) Web Age Solutions Inc. 2010

6-9
9

Handling Events

We can register on or more event handler functions for a


particular event for a particular Dom element. When the
event takes place in that element, the event handler
functions are automatically called by the JavaScript
engine.
There are three ways to register an event handler:

By setting one of the event handler properties for the element in


the HTML markup, such as the "onclick" attribute of the
<button> element.
By setting the same property for the DOM element object DOM.
By calling the addEventListener()/attachEvent() method of the
element for which the handler should be attached.

(C) Web Age Solutions Inc. 2010

6-10

Register Using HTML Markup

An event property takes an arbitrary JavaScript expression that is


evaluated when the event takes place.

Two special variables are available to such an expression event and


this.
The "event" variable points to the DOM Event object that has fired.

<button onclick="alert('Event fired'); func1();">OK</button>

<button onclick="func2(event)">OK</button>
Here, event is a special keyword that instructs the browser to supply the
event object as the first parameter. Another example that uses the "this"
keyword as well.

The "this" keyword points to the DOM Element object for which the
event handler was registered. Due to bubbling, this may or may not be
the actual element where the event took place.

The expression must be valid at the time the event fires.

<button onclick="func2(this, event)">OK</button>


<button onclick="func3(event, myObj)">OK</button> myObj must be
a valid variable when the event fires and not when the HTML markup is
parsed.

function func1() {
//This is the most common type
}
function func2(e) {
//Get event properties
var x = e.clientX;
var y = e.clientY;
}
function func3(e, data1, data2) {
//data1 should be "Hello"
//data2 should be "World"
}

(C) Web Age Solutions Inc. 2010

6-11
11

Register Using Element


Property

You can also set the event handler properties:

The event handler properties are in all lowercase and match the
corresponding attributes in XHTML (such as onlick, onkeydown,
onload etc.).
The problem is, this way, the function can not receive the event
parameter.

var e = document.getElementById("b1");
e.onclick = func1;

FireFox (Mozilla) provides a work around, see below. IE does not have
any work around.

If you wish to set the event handler from JavaScript and wish to
access the event object from the handler method, register the event
using an API call.

This is discussed in the next slide.

No Event Supplied
function func1(event) {
//event will be null for Mozilla and IE
}
FireFox Work Around
Register an anonymous function that will receive the event object as
argument.
e.onclick = function(evt) {sendRequest(evt);};
function sendRequest(event) {

(C) Web Age Solutions Inc. 2010

6-12
12

Register Using DOM API

In Mozilla, call the addEventListener method for the element firing


the event to register a handler.

addEventListener(name, handler, capture)

In IE, call the attachEvent method of the element firing the event.

attachEvent(name, handler)

name The type name of the event. Such as "click", "change" or "load".
handler The function handling the event. Receives the event object.
capture If true, the parents of this element will not get the event. usually
set to false.

name The type name of the event. Such as "onclick", "onchange" and
"onload".
handler The event handler function. Receives the event object.

This way, you can attach as many event handlers as you want. See
example below. The order of invocation of the event handlers can
be browser dependent.

//Functions registered this way have access to the


//event object
function func1(evt) {
alert("func1");
}
function func2() {
alert("func2");
}
function registerMozillaEvents() {
var b1 = document.getElementById("b1");
b1.addEventListener("click", func1, false);
b1.addEventListener("click", func2, false);
}
function registerIEEvents() {
var b1 = document.getElementById("b1");
b1.attachEvent("onclick", func1);
b1.attachEvent("onclick", func2);
}
<button id="b1">Button One</button>

(C) Web Age Solutions Inc. 2010

6-13
13

Example: Register Using DOM API


//Attach an onload event handler
if (window.attachEvent) {
//IE
window.attachEvent("onload", initApp);
} else {
//Mozilla
window.addEventListener("load", initApp, false);
}
function initApp(e) { Note, the handler receives the event fired.
//
}

The example above shows how to register an event handler in a browser


neutral manner using the DOM API. In this case, we are attaching an event
handler for the onload event of the body.

(C) Web Age Solutions Inc. 2010

6-14

Best Practice
Generally, do not use XHTML markup to register an event handler.
Use DOM API to externalize the handler registration way from the
XHTML markup.
function registerIEEvents() {
var b1 = document.getElementById("b1");
b1.attachEvent("onclick", func1);
b1.attachEvent("onclick", func2);
External JavaScript
}
File

window.onload = registerIEEvents;

<button id="b1">Button One</button>

The XHTML File

As you can see above, the XHTML becomes very clean. You don't have worry
about the different function names and event handler properties. All that
details can be externalized in a separate JavaScript file. As an added benefit,
you can attach multiple event handlers for the same event.
You can either use the attachEvent or addEventListener method or set the
event handler properties. Using the latter, approach, the Javascript code will
look like this:
function registerIEEvents() {
var b1 = document.getElementById("b1");
b1.onclick = func1;
}
This approach is browser neutral, but we can only attach one handler.

(C) Web Age Solutions Inc. 2010

6-15
15

Canceling Default Action

Some events lead to special browser behavior called default action.


For example:

For an <href> element, the "onclick" event leads to a new document


being loaded.
For an <input> element, the "onkeypress" event leads to a new
character being inserted (or deleted if backspace key is pressed).
For a <form> element, the "onsubmit" event leads to the form being
submitted.

An event handler function can return false to disable the default


action from being taken. This works in Mozilla and IE. In Mozilla, you
can also call the preventDefault() method of the event object to
achieve the same goal.
<form onsubmit="return validateForm();" >
<input type="text" onkeypress="return validateEntry(event);"/>

(C) Web Age Solutions Inc. 2010

6-16

Working With Styles

Cascading Style Sheet (CSS) gives us ways to manipulate the


look and feel of element.

Style can be applied to an element in two ways:

We will learn about CSS2 in details later. Here, we will discuss how
to manipulate styles using the DOM API.
The DOM API allows us to dynamically change the style of an
element. This leads to powerful visual effects in an AJAX based
application.
Directly using the style attribute of the element.
By defining a style rule in a style sheet.

The DOM API allows us to change the style for an individual


element or change a style rule.

The latter allows us to change the look of all elements for which
the rule applies.

Style Rule
The most common style rule is class definition. A set of styles are defined for a
class. The class name is set for an element using its class attribute.
<style type="text/css" title="Basic Styles">
p.note {
color: red;
background: yellow;
font-weight: bold;
}
</style>
<p class="note">This is p.note</p>

(C) Web Age Solutions Inc. 2010

6-17
17

Example
Styles defined for rules in a stylesheet
<style type="text/css" title="Basic Styles">
h2 {
font-size: 110%;
Rule 1
color: red;
background: white;
}
p.note {
color: red;
Rule 2
background: yellow;
font-weight: bold;
}
</style>

Styles defined for an element


<div id="popup" style="position:absolute;visibility: hidden;width: 200px;height:
150px;background: yellow;"></div>

As we can see above, a set of styling attributes can be defined:


1. For a style rule in a stylesheet. Each rule has a selector, such as "h2" and
"p.note"
2. For an element.
Examples of styling attributes are "font-size", "background" and "position".
A collection of styling attributes is called a style and represented by the DOM
Style object. This will be discussed next.

(C) Web Age Solutions Inc. 2010

6-18
18

The Style Object

A Style object represents a collection of styling


attributes, such as "background" and "font-weight".
A Style object is associated with every element and
can be accessed using the element's style property:

var s = element.style;

Style objects are also used in a style sheet as follows

A document contains a collection of style sheets.


Each style sheet has a collection of rules.
Some of the rules are style rules (you can also have import
rules that import an external style sheet URL). Each style
rule has a Style object associated with it. A rule also has a
selector, such as a class name, that is used to locate the
elements for which the style should be applied.

More on selectors and import rules will come in a latter chapter. For now, just
think of the class name selector that we have see in the previous slide. CSS2
allows for more complex selectors. A selector is eventually used to determine
which elements will be eligible for a particular rule. System will apply the rule's
style to these elements.

(C) Web Age Solutions Inc. 2010

6-19
19

The Style Object

The properties of this object represent the


styling attributes. For example:

color Represents the color style attribute.


borderTopColor Represents "border-top-color".

Note how the dashes are converted to upper case in the


Style object attribute name.

backgroundColor Represents "backgroundcolor".

We will discuss a more complete list of styling


attributes in a separate CSS chapter.

(C) Web Age Solutions Inc. 2010

6-20

Setting Style of an Element

Two ways to do this:

Set the style attribute as a whole.


Set individual styling attribute of the Style object.

Setting the whole style


element.style.cssText = "color: red; background-color: blue";
element.setAttribute("style", "color: red; background-color: blue"); //Same

This will wipe out all other styles and only set these styles. Generally, this is not
recommended, but may be faster than setting many styles separately.

Setting individual styling attributes


element.style.color = "red";
element.style.backgroundColor = "blue";

When setting coordinate and size attributes, make sure that you specify the
unit.
element.style.top = "100px"; //This will work
element.style.top = "100"; //This will not work and will be ignored

Setting individual styling attribute preserves all other styling attributes. As a


result, this is the recommended approach.

(C) Web Age Solutions Inc. 2010

6-21
21

Working With Style Sheets

To get an array of StyleSheet DOM objects


used by a document, use the
document.styleSheets property.
Key properties of a StyleSheet object:

title The title of the style sheet. Can be used to


identify the style sheet. See example below.
Mozilla: cssRules, IE: rules Returns an array of
Rule objects. Rule object will be discussed shortly.

Getting a List of Style Sheets


var sheetList = document.styleSheets;
for (var i = 0; i < sheetList.length; ++i) {
var sheet = sheetList[i];
alert(sheet.title);
var rules;
if (sheet.rules) {
rules = sheet.rules; //IE
} else {
rules = sheet.cssRules; //Mozilla
}
}
Title of a Style Sheet
<style type="text/css" title="Basic Styles">
p{
font-family: Arial;
}
</style>

(C) Web Age Solutions Inc. 2010

6-22
22

Working With Style Sheets

Key methods of StyleSheet object.

IE: addRule(selector, rule_body [, index]) Adds


a new rule to the style sheet. Here, rule_body is
what goes inside the curly bracket. If index is
specified, the rule is added at that position (0 for
the very top).
Mozilla: insertRule(rule, index) Here, rule is the
whole rule including the selector.
IE: removeRule(index) Removes a rule at
position index.
Mozilla: deleteRule(index)

IE Example
sheet.addRule("h2", "font-size: 110%; color: red; background: white;");
sheet.addRule("h2", "font-size: 110%; color: red; background: white;", 0);
//Insert at the top
Mozilla Example
sheet.insertRule("h2 {font-size: 110%; color: red; background: white;}", 0);

(C) Web Age Solutions Inc. 2010

6-23
23

Working With Style Sheets

Key properties of a Rule object

type Indicates the type of rule. Mozilla only.

1 for style rule. 5 for import rule etc.

selectorText The selector associated with this


rule.
style The style object of this rule.

Changing any attribute of the style of a Rule


object will affect the look of all elements for
which the rule applies.

var rules;
if (sheet.rules) {
rules = sheet.rules; //IE
} else {
rules = sheet.cssRules; //Mozilla
}
for (var k = 0; k < rules.length; ++k) {
rule = rules[k];
if (rule.selectorText == "p.note") {
rule.style.backgroundColor = "green";
}
}

(C) Web Age Solutions Inc. 2010

6-24
24

DOM HTML API

W3C provides an object model to represent the XHTML tag. For


example, the <table> element is represented by the
HTMLTableElement data type.

All elements in a page are stored as a DOM tree. The "document"


global variable represents this DOM document.
To create a new HTML object use the createElement() method of the
DOM document. Supply the tag name as the only parameter.
Example, to create a new HTMLTableElement object do:

Each data type has a set of properties, events and methods. We will discuss
the most common HTML data types in this chapter.
All HTML data types inherit from the Element object which we have already
discussed in a previous chapter.

var t = document.createElement("table");
var row = t.insertRow(0); //returns a HTMLTableRow object

Using the DOM HTML API, you can dynamically add, remove or
manipulate a page and create a feature rich application.

You don't explicitly use the data type name in JavaScript. For example, this will
not work:
var t = new HTMLTableElement(); //Will not work
var t = document.createElement("table"); //This will work
//More example
var s = document.createElement("select"); //Returns a HTMLSelectElement
object

(C) Web Age Solutions Inc. 2010

6-25
25

Table DOM Objects

Various objects, all extended from the


Element object, make up a table.

HTMLTableElement object represents the whole


table (the <table> element).
HTMLTableRowElement object represents a row
(<tr> element).
HTMLTableCellElement object represents a cell
(<td> element).

Knowing this DOM API, you can dynamically


construct a table.

This can prove very useful in AJAX programming.

These elements inherit all the methods and properties of the Element object. A
table can be looked up from a document like any other element (that is, by
calling getElementById()).

(C) Web Age Solutions Inc. 2010

6-26
26

The HTMLTableElement
Object

Key properties:

rows Returns an array of HTMLRowElement objects. This


includes the row in the <thead> and <tfoot> elements, if
they exist.
width, bgColor, cellSpacing, cellPadding Correspond to the
various attributes of the <table> element. Watch out for the
mixed case in the property names (where as the attribute
names are all in lower case).

Key methods:

insertRow(index) Inserts a new row at the given index.


Returns a new HTMLRowElement object.
deleteRow(index) Deletes the row at a given index.

(C) Web Age Solutions Inc. 2010

6-27

The HTMLTableRowElement
Object

Key properties:

cells Returns an array of HTMLTableCellElement objects.


rowIndex Position of the row starting with 0. The position
counts any header row (<thead>) that the table might
have.
align, vAlign, bgColor Correspond to the attributes of the
<tr> element.

Key methods:

insertCell(index) Adds a new cell at the given position.


Returns a HTMLTableCellElement object.
deleteCell(index) Removes a cell.

(C) Web Age Solutions Inc. 2010

6-28

The HTMLTableCellElement
Object

Key properties:

cellIndex Position of the cell, starting


with 0.
align, colSpan, rowSpan, vAlign, width
Correspond to the <td> attributes.
innerHTML Text shown in the cell.

(C) Web Age Solutions Inc. 2010

6-29

Example of Table DOM API


function addProduct() {
var table = document.getElementById("product_list");
var sku = document.getElementById("sku").value;
var price = document.getElementById("price").value;
var rowCount = table.rows.length;
var newRow = table.insertRow(rowCount);//Append row
var cell = newRow.insertCell(0);
cell.innerHTML = price;
cell = newRow.insertCell(0);
cell.innerHTML = sku;
}

<table id="product_list" cellspacing="10">


<thead>
<tr>
<td>Product SKU</td> <td>Price</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p>
Product SKU: <input type="text" id="sku" size="20"/><br/>
Price: <input type="text" id="price" size="20"/><br/>
<button onclick="addProduct();">Add Product</button>
</p>

(C) Web Age Solutions Inc. 2010

6-30
30

The Form Element Objects

A HTMLFormElement object represents the <form>


tag.
The <input> element is represented by the
HTMLInputElement object.
The <select> element is represented by the
HTMLSelectElement object.
The <option> element is represented by the
HTMLOptionElement object.
All of these objects extend the base Element object.
Knowing the DOM API for the form objects will help
you manipulate a form.

(C) Web Age Solutions Inc. 2010

6-31

The HTMLFormElement Object

Key properties:

elements Returns an array of form control


elements.
name, method, action Corresponds to the
<form> element attributes.

Methods:

submit() Submits the form. This causes the


browser to send a HTTP request. The page sent
by the server is then displayed.
reset() Set the form controls to their original
state.

The elements property returns a collection of input elements only. Compared


to that, the childNodes property returns all children elements including
elements that are not form controls, such as <table> and <p>.

(C) Web Age Solutions Inc. 2010

6-32
32

The HTMLInputElement
Object

A large number of input control types are created using the <input>
element.
Key properties:

type Corresponds to the type attribute of <input> element. For example,


"submit" or "text".
defaultValue The original value shown by the control. This can not be
changed.
value The value entered by the user.
defaultChecked A boolean property indicating the original state of a check
box.
checked A boolean value indicating if a check box is checked.
form The HTMLFormElement object that contains this element.

Key methods:

click() Simulates a user click. For "button", "checkbox", "radio", "reset", or


"submit" types only.
focus() Gives keyboard focus to this element.

(C) Web Age Solutions Inc. 2010

6-33

The HTMLSelectElement
Object

Key properties:

options An array of HTMLOptionElement objects.


selectedIndex - Index of the option currently selected.
value The value of the currently selected option.
multiple A boolean value indicating if multiple options can be
selected.
size Number of options displayed at a time.

Methods:

add(newOption, beforeOption) Adds a new option object before


an existing option object. Set beforeOption to null to add the new
option at the end. Alternatively use the appendChild method of the
Element interface. Mozilla only.
add(newOption) IE only.
remove(index) Removes an option at a given index.

Examples
//Delete all options in a drop down list
var countrySelect = document.getElementById("country");
//Clear options
while (countrySelect.options.length > 0) {
countrySelect.remove(0);
}
//Add a new country option
var option = document.createElement("option");
option.text = "Canada";
option.value = "CA";
try {
countrySelect.add(option, null);
} catch (e) {
//IE
countrySelect.add(option);
}

(C) Web Age Solutions Inc. 2010

6-34
34

The HTMLOptionElement
Element

Key properties:

text The body text of the element. This is


displayed to the user.
value The value associated with the option.
disabled Makes the option unselectable.
selected Boolean value indicating if the option is
selected.
defaultSelected Boolean value indicating if the
option was originally selected wen the form was
first displayed.
index The location of the option in the select
element.

(C) Web Age Solutions Inc. 2010

6-35

Review Questions
1.

2.
3.

4.
5.

T/F: Event creation is done the same


way if you're using Mozilla and IE.
What is event bubbling?
What are the three ways for registering
an event handler?
What do style sheets consist of?
T/F: Making a change to a style rule
impacts a single element on a page.

(C) Web Age Solutions Inc. 2010

6-36

Review Questions
6.

7.

What are some examples of


manipulations you can do using the
DOM HTML API to a downloaded
page?
T/F: You can see the changes to the
DOM when you view the source code
for a page in the browser.

(C) Web Age Solutions Inc. 2010

6-37

Review Answers
1.

2.

False. It's done in a browser


dependent fashion, depending on
whether you're using a Mozilla browser
(Firefox or Netscape) or IE.
Event bubbling occurs when an event is
fired and is handled by any event
handlers for that element (e.g., td), as
well as all its ancestors' event handlers
(e.g, tr, table) in the DOM tree. Not
all events bubble up the chain.

(C) Web Age Solutions Inc. 2010

6-38

Review Answers
3.

The 3 ways for registering an event handler


are:

4.
5.

By setting the event handler properties of the


element, such as onclick
By setting the same property using the DOM API
By calling the addEventListener
(Mozilla)/attachEvent (IE) method of the
element for which the handler should be attached

Style rules
False. It affects the look of all elements for
which that rule applies.

(C) Web Age Solutions Inc. 2010

6-39

Review Answers
6.

7.

Adding/removing rows to/from a table and


clearing/populating a drop-down list.
False. The DOM is stored in the browser's
memory. It's only visible using a special tool
(e.g., Firebug for Firefox).

(C) Web Age Solutions Inc. 2010

6-40

WA1503 Comprehensive AJAX

WA1503 Comprehensive AJAX


Communication With Server Basic

(C) Web Age Solutions Inc. 2010

7-1

WA1503 Comprehensive AJAX

Introduction

In an AJAX application, the application code in the browser


(JavaScript) acts as the client.

Actual business task processing happens in a server.


The AJAX application interacts with a server for two purposes:

The client is primarily focused on rendering information and


accepting user input.

To retrieve information and display that to the user. For example,


show a list of past orders in a grid.
To request a business task to be performed. For example, place a
new order or cancel an order.

In this chapter, we will discuss the various mechanisms that you


can use to implement the client server communication.

(C) Web Age Solutions Inc. 2010

7-2

WA1503 Comprehensive AJAX

Application Layer Protocol

AJAX applications use HTTP(s) as the presentation layer


protocol.
For the application layer (data format), no standard exists.

Application layer protocol deals with how data should be formatted


for the client-server interaction.
This chapter will focus on the various options available for this
layer.

You have several choices for the application layer protocol:

Plain HTML snippets.


XML document.
SOAP (Web Services).
Direct Web Remoting (DWR).
JavaScript Object Notation (JSON).

Application layer protocol deals with the data format of the communication.
This is also known as the Remote Procedure Call (RPC) mechanism. In
this mechanism, the client invokes a specific operation or method of the
server side application. For example, placeOrder or cancelOrder. An
operation may take any number of input parameter data. As a result, a
typical request contains the following information:
1. The operation name that should be invoked.
2. The input data (Optional).
3. User's identifier (Optional).
The operation may return data back.

(C) Web Age Solutions Inc. 2010

7-3

WA1503 Comprehensive AJAX

Application Layer Protocol


Client

Server

Application Layer
(XML, DWR, SOAP, JSON)

Application Layer
(XML, DWR, SOAP, JSON)

Presentation Layer
(HTTP)

Presentation Layer
(HTTP)

Session, Transport,
Network Layer etc.
(TCP/IP)

Session, Transport,
Network Layer etc.
(TCP/IP)

Open Systems Interconnection (OSI) Reference Model captures how data is


transferred in client server interaction.
First the application code (client or server side), formats data in the application
layer. For example, this can be an XML document. The data is then
augmented by the presentation layer. For example, for HTTP, the request
header information is added.
The remaining low level layers (such as session and transport) add their own
data on top of what the application code had created. The data is then finally
sent over the physical layer. The physical layer is composed of cables and
electrical voltages. When the data reaches the other side (client or server), it
goes through the same set of layers but in reverse order. Each layer uses the
data attached by the corresponding layer on the other side.
The presentation layer on the receiving end will cause a server side code to be
executed. The server side code may be a Servlet, JSP, PHP or ASP page.
The application code then processes the application level data (the same data
that was created by the application layer of the other side).

(C) Web Age Solutions Inc. 2010

7-4

WA1503 Comprehensive AJAX

Plain HTML Snippet

This is the simplest of all protocols.


The client (JavaScript code), sends a HTTP
GET or POST request.
The server sends back an HTML snippet.
The snippet contains data that should be
shown to the user.

This data is typically shown as the innerHTML


property of an element.

(C) Web Age Solutions Inc. 2010

7-5

WA1503 Comprehensive AJAX

Plain HTML Snippet

In the server side, write the Servlet, JSP, PHP


or ASP page just like a normal web
application.
Except, instead of generating a full HTML
page, produce a portion of a page.
For example, let us say that a customer
wishes to view a list of past orders, the server
side code will return the data as a <table>
element.

The client will display the table in a <div>


element.

(C) Web Age Solutions Inc. 2010

7-6

WA1503 Comprehensive AJAX

Plain HTML Snippet

Advantages:

Disadvantages:

Very easy to implement.


The look and feel logic gets divided between the
client and the server.
The entire reply of the server is set as innerHTML
of an element. That means, we can not update
different areas of the page with pieces of data in
the reply.

Generally recommended for simple client


server interaction.

(C) Web Age Solutions Inc. 2010

7-7

WA1503 Comprehensive AJAX

XML Document

In this approach, the client sends input data as a part of the


request in one of two ways:

As POST body or GET URL parameter.


As an XML document.

The server returns a XML document as reply.

The content type of the reply must be set to "application/xml" or


"text/xml".

Upon receiving the reply, the XML HTTP request object


automatically parses the XML text and creates a DOM structure.

The client can iterate through the DOM document and display
data from various elements in the document inside various
elements in the page.
An example of an XML document returned by the server is
shown below.

This DOM is made available through the responseXML property.

Example
Let us say that the server returns a list of past orders placed by the user as the
following XML document:
<order_list>
<order id="10001" date="10/10/2005" status="SHIPPED"/>
<order id="10053" date="11/9/2005" status="PENDING"/>
</order_list>
The client code will need to iterate through all <order> elements and show
various properties of the order in a table cell.

(C) Web Age Solutions Inc. 2010

7-8

WA1503 Comprehensive AJAX

XML Document Server Side

In the server side, use an appropriate XML API to


form a DOM document that will contain the reply
data.

In Java and .NET there are standard API available to form a


DOM document.
here, we will discuss both C# and Java API to produce a
DOM document in the server side. Instructor: Please cover
only the API suitable for the students.
Avoid using string concatenation to form the reply XML
document.

Then serialize the DOM document in the HTTP reply


stream.

(C) Web Age Solutions Inc. 2010

7-9

WA1503 Comprehensive AJAX

Example: Build DOM Document in


Java
import javax.xml.parsers.*;
import org.w3c.dom.*;
Document buildDOMDocument() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element list = (Element) document.createElement("order_list");
document.appendChild(list);
Element order = document.createElement("order");
order.setAttribute("id", "10001");
order.setAttribute("date", "11/9/2005");
order.setAttribute("status", "SHIPPED");
list.appendChild((Node) order);
return document;
}

The example above shows how to create a DOM document for the
order list in the server side. Next, we will learn how to write the
document in the HTTP reply stream.

(C) Web Age Solutions Inc. 2010

7-10

WA1503 Comprehensive AJAX

Example: Write DOM


Document in HTTP Reply
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
//
void writeDocument(Document doc, OutputStream out) throws Exception {
Source source = new DOMSource(doc);
// Prepare the output result
Result result = new StreamResult(out);
// Get Transformer
Transformer xformer = TransformerFactory.newInstance().newTransformer();
// Write to the stream
xformer.transform(source, result);
}

The example above shows how to write a DOM document in a HTTP


reply stream. The OutputStream object represents the reply stream.
Later, we will see how a Servlet builds the document and writes it to the
reply.

(C) Web Age Solutions Inc. 2010

7-11

WA1503 Comprehensive AJAX

Example: The Servlet


protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("application/xml");
OutputStream out = response.getOutputStream();
try {
Document doc = buildDOMDocument();
writeDocument(doc, out);
} catch (Exception e) {
e.printStackTrace();
}
}

In the example above, the doGet method of a Servlet acts as follows:


1. It sets the content type of the reply to "application/xml".
2. Obtains the OutputStream object from the response object.
3. Builds the reply DOM document.
4. Writes the DOM document in the reply stream.
Note: Here we work with the OutputStream object of the reply. We could have
also worked with the PrintWriter object by calling response.getWriter. The
PrintWriter object is not recommended as it may not be able to encode the
XML using UTF-8 properly.

(C) Web Age Solutions Inc. 2010

7-12

WA1503 Comprehensive AJAX

C#: Create a XML DOM


Document
using System.Xml;
using System.IO;
public static WriteOrderXML(Stream output) {
XmlWriter w = XmlWriter.Create(output);
w.WriteStartDocument();
w.WriteStartElement("order_list");
w.WriteStartElement("order");
w.WriteAttributeString("id", "10001");
w.WriteAttributeString("date", "11/9/2005");
w.WriteAttributeString("status", "SHIPPED");
w.WriteEndElement();
w.WriteEndElement(); //End order_list
w.WriteEndDocument();
w.Flush(); //Very important
}

Here, we are using a XmlWriter object to directly output an XML document to


an output stream. The following line creates a new XmlWriter object that writes
the document to a Stream object. Later, we will learn how to write to the HTTP
reply stream.
XmlWriter w = XmlWriter.Create(output);
The WriteStartDocument() and WriteEndDocument() methods of the writer
starts and ends a document. The WriteStartElement() function starts a new
element and WriteEndElement() ends it. The WriteAttributeString() adds a new
attribute to the current element.
The call to the Flush() method is very important. The writer object may cache
parts of the document in memory. Unless Flush() is called, the document may
not be completely written to the stream.

(C) Web Age Solutions Inc. 2010

7-13

WA1503 Comprehensive AJAX

C#: Output XML in HTTP


Reply
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/xml";
OrderManager.WriteOrderXML(
Response.OutputStream);
}

Here we see the Page_Load() method of a codebehind class. First, it sets the
content type of the reply to "application/xml". Next, it calls the WriteOrderXML
method that we have developed in the previous slide. Notice, that, as the
Stream object it supplies the HTTP reply stream. This causes the
WriteOrderXML function to directly write the XML to the HTTP reply. This is
one of the most efficient ways to output a large XML to the browser.

(C) Web Age Solutions Inc. 2010

7-14

WA1503 Comprehensive AJAX

XML Document - Client Side

Once the reply from the server is received, the


request object parses it out and constructs a DOM
document object.
The client code obtains the DOM document object
using the responseXML property of the request.
The DOM document object follows the same API as
the XHTML document object.

We have already discussed this API in detail in a separate


chapter.

The client uses the DOM API to iterate through all


the elements in the document and retrieve data. This
data is then rendered in the page.

The example below shows each order using a <p> tag inside of a <div> tag
with id "result".
function handleReply(r) {
var doc = r.responseXML;
var order_list = doc.documentElement;
var orders = order_list.childNodes;
var theDiv = document.getElementById("result");
for (var i = 0; i < orders.length; ++i) {
var order = orders[i];
var text;
text = "<b>ID:</b> " + order.getAttribute("id") +
" <b>Placed on:</b> " + order.getAttribute("date") +
" <b>Status:</b> " + order.getAttribute("status");
var p = document.createElement("p");
p.innerHTML = text;
theDiv.appendChild(p);
}
}

(C) Web Age Solutions Inc. 2010

7-15

WA1503 Comprehensive AJAX

DOM API Summary

We have already encountered the DOM API when we learned


about the XHTML document object.
The API is not limited to just the XHTML document that is
rendered by the browser. You can use the DOM API to work
with any XML document.

Here, we will summarize the most popular properties and


methods of various objects.

In the current case, we use the API to navigate the XML document
returned by the server.

For details, refer to the XHTML chapter. Or see:


http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html and
http://www.w3.org/TR/DOM-Level-2-Core/core.html.

A sophisticated client will send a XML document as request


data. We will learn how to create a new XML document from
scratch and send it to the server.

XML as request data


So far, we have been sending request data to the server as URL parameters
(GET request) or as request body data (name1=value1&name2=value2).
A more complex client may wish to send a XML document as request data.
You can send a complex data structure this way. For example, a user may
make an expense claim. The entire expense claim information can be sent as
an XML document. Doing this using HTTP post data or URL parameter can be
difficult.

(C) Web Age Solutions Inc. 2010

7-16

WA1503 Comprehensive AJAX

DOM API The Document


Object

The DOM document object is obtained by using the


responseXML property of the request object.
A new DOM document can also be created from scratch. This is
usually done when a client wishes to send an XML document as
HTTP request data.
Properties:

Methods:

documentElement The root level element.


getElementsByTagName(tag) Returns an array of elements that
match the tag name, such as "order".
createElement(tag) Returns a newly created element with a given
tag name. This element must be added to another element as a
child to be a part of the document.
createTextNode(text) Create a new node containing the body
text of an element.

We will learn how to create a new XML document shortly.

(C) Web Age Solutions Inc. 2010

7-17

WA1503 Comprehensive AJAX

DOM API The Element


Object

The Element object represents a tag in the XML document (such


as <order>).
Properties:

nodeType Type of node. See details below.


nodeName The tag name.
childNodes An array of child elements.
firstChild the first child element.
nodeValue See details below.

Methods:

appendChild(element) Add a new child element.


removeChild(element) Remove a child element.
getAttribute(name) Returen the value of an attribute.
setAttribute(name, value) Set the value of an attribute.
removeAttribute(name) Remove an attribute.

Node Types
Almost everything in a DOM document (including the document itself) is a
node. Each node is a leaf in the tree like structure that a DOM document is.
For example, the attributes of an element are also nodes. If an element has
body text, it is represented by one or more text nodes. Common node types
are:
1 A regular element. nodeValue is null.
2 Attribute. nodeValue is the value of the attribute.
3 Body text of an element. nodeValue is the text contained by this node.

(C) Web Age Solutions Inc. 2010

7-18

WA1503 Comprehensive AJAX

Body Text of an Element

Data in XML is specified either as attributes of an element or as the


body text of an element.
If the body text is small, access it using the textContent (Mozilla) or
text (IE) property of the Element. Note: In IE, the innerText property
works for HTML documents only. For generic DOM elements, use the
text property.
The amount of body text may be very large. To optimize parsing, DOM
API represents the body text as one or more text nodes that are
children of the element for which body text is specified.

The number of text nodes and how the body text will be chunked up
between them is totally dependent on the browser and the amount of body
text.

<comments>
nodeType: 1
<comments>
Hello fantastic world!
</comments>

nodeValue: Hello fantastic


nodeType: 3

nodeValue: world!
nodeType: 3

innerText vs. text in IE


If you have an HTML document, you can access the text of an element (such
as <p> or <div>) using the innerText property of the element. For generic DOM
documents (returned by the responseXML of the XmlHttpRequest), use the
text property of an element instead.
How DOM API Optimizes Text Handling?
DOM API optimizes handling of large amounts of body text by chunking it up in
multiple text nodes. When creating a new node, we can append body text bit
by bit, instead of creating one large string. Similarly, when reading the body
text, we read the value of one text node at a time. In both cases, we avoid
having to create a very large string to hold the data.
The downside is that, there is no easy way to quickly get or set the entire body
text. To read the body text of an element, we must iterate through all its
children nodes that are of type 3.

(C) Web Age Solutions Inc. 2010

7-19

WA1503 Comprehensive AJAX

Setting Body Text


var e = document.createElement("comments");
var txt1 = document.createTextNode("Hello
fantastic ");
var txt2 = document.createTextNode("world!");
e.appendChild(txt1);
e.appendChild(txt2);

The example above shows how to set the body text of an element in chunks.
We didn't have to create two separate text nodes. Certainly, the following will
have the same effect:
var txt = document.createTextNode("Hello fantastic world!");
e.appendChild(txt);

(C) Web Age Solutions Inc. 2010

7-20

WA1503 Comprehensive AJAX

Displaying Body Text


var ta = document.createElement("textarea");
ta.setAttribute("rows", "10");
ta.setAttribute("cols", "50");
theDiv.appendChild(ta);
var notes = doc.getElementsByTagName("comments")[0];
for (var i = 0; i < notes.childNodes.length; ++i) {
var n = notes.childNodes[i];
logger.trace("Child node type: " + n.nodeType);
if (n.nodeType == 3) {
var txt = document.createTextNode(n.nodeValue);
ta.appendChild(txt);
}
}

In the example above, we are showing the body text of the <comments>
element using a <textarea> element.
Note, here the "doc" variable represents the DOM document returned by the
server. The "document" variable represents the XHTML document rendered as
a page by the browser.
We iterate through all the children nodes of the "comments" element. If the
nodeType of a child is 3, it indicates a text node. For each text node, we create
a new text node and append it as a child of the <textarea> element.
Note: You may think of directly appending a text node from one document as
a child of an element in another document. For example:
if (n.nodeType == 3) {
ta.appendChild(n);
}
This works fine in FireFox but not in IE. Which is rather unfortunate. Since the
code above will work much faster as we are not creating new text nodes.

(C) Web Age Solutions Inc. 2010

7-21

WA1503 Comprehensive AJAX

Using XML As Request Data

A complex and rich AJAX application may need to send a


complex data structure as a part of a HTTP request.
For example, we can build a shopping cart using AJAX. The user
adds items to the cart. When the order is placed, we need to
send information about the user and all the items in the cart
and shipping address to the server.
Using an XML document will simplify the formation of the
request data instead of using the HTTP POST data convention.

The latter uses a simple name value pair pattern. XML can allow for
a more sophisticated data structure.

On the server side, we can use an XML parser to interpret the


data.
Next, we will learn how to create a new XML document and
send it as an HTTP request data.

The XML document will be sent using a HTTP POST request. The body will
look something like this:
xml=<order><item id="101" date="10/13/2006"></order>

(C) Web Age Solutions Inc. 2010

7-22

WA1503 Comprehensive AJAX

Creating a New DOM


Document

This is usually needed if you wish to send an XML


document as HTTP request data.
In Mozilla, a new document is created using the
DOMImplementation object.

This object is obtained using the document.implementation


property.
The createDocument method of the implementation object is
used. This method takes three parameters:

namespaceURI The namespace URI of the document. Can be


"".
rootElement The name of the root element. System
automatically creates this element which can be obtained using
the documentElement property.
documentType usually null.

Mozilla Example
var doc = document.implementation.createDocument("", "order_list", null);
var e = doc.createElement("order");
e.setAttribute("id", "101");
e.setAttribute("date", "10/13/2006");
doc.documentElement.appendChild(e);
e = doc.createElement("order");
e.setAttribute("id", "102");
e.setAttribute("date", "10/13/2006");
doc.documentElement.appendChild(e);

(C) Web Age Solutions Inc. 2010

7-23

WA1503 Comprehensive AJAX

Creating a New DOM


Document

In IE, the "Microsoft.XMLDOM" ActiveX


object represents a DOM document.
When this object is first created, no
root level element exists. You must
create it and append to the document.

See example below.

doc = new ActiveXObject("Microsoft.XMLDOM");


var root = doc.createElement("order_list");
doc.appendChild(root);
var e = doc.createElement("order");
e.setAttribute("id", "101");
e.setAttribute("date", "10/13/2006");
doc.documentElement.appendChild(e);
e = doc.createElement("order");
e.setAttribute("id", "102");
e.setAttribute("placedOn", "10/13/2006");
doc.documentElement.appendChild(e);

(C) Web Age Solutions Inc. 2010

7-24

WA1503 Comprehensive AJAX

Creating a New DOM


Document
function createDocument(rootElement) {
var v;
try {
//For IE
v = new ActiveXObject("Microsoft.XMLDOM");
var root = v.createElement(rootElement);
v.appendChild(root);
} catch (e) {
//For Mozilla
v = document.implementation.createDocument("", rootElement, null);
}
if (v == null)
throw new Error("DOM API not supported");
return v;
}

The function above returns a new DOM document in a browser neutral


fashion. The function takes the rootElement parameter that is the name of the
root element in the document. Example usage:
var doc = createDocument("order_list");

(C) Web Age Solutions Inc. 2010

7-25

WA1503 Comprehensive AJAX

Serializing DOM Document as


Text

Before we can send the XML document as HTTP


request data, we must convert it to text.
In Mozilla, the XMLSerializer object is used. The
serializeToString(doc) method returns the XML text.
In IE, the DOM document object has a property
called xml that returns the string.
See example below on how to obtain the XML text
from a DOM document in a browser neutral fashion.
Before you send the XML string to the server, you
must escape special characters such as & and <
using the escape() JavaScript function.

function getXMLString(doc) {
var xml = null;
try {
//Mozilla
var ser = new XMLSerializer();
xml = ser.serializeToString(doc);
} catch (e) {
//IE
xml = doc.xml;
}
return xml;
}

(C) Web Age Solutions Inc. 2010

7-26

WA1503 Comprehensive AJAX

Posting an XML Document


function ajaxPostDocument(url, doc, onLoad, data) {
var xhr = createRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status == 200) {
onLoad(xhr, data);
}
xhr = null; //Prevent memory leak in IE
}
}
var xml = getXMLString(doc);
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
xhr.send("xml=" + escape(xml));
}

Above, we see an utility method called ajaxPostDocument that posts a DOM


document to make a HTTP request. It behaves very similar to the
ajaxGet(0 method we have see in a previous chapter. It takes four
parameters:
1. url The URL that will be requested.
2. doc The DOM document object that will be sent.
3. onLoad A function that will be invoked when reply from the server is
completely received.
4. data Arbitrary data that will be passed to the onLoad function when it is
invoked.
A few things to note about this function:
1. We obtain the XML text for the DOM document by calling the
getXMLString() utility method. We have seen this method earlier in this
chapter.
2. The XML text is sent as a part of the request body. The name of the
parameter is "xml".
3. We escape the XML text using the escape() function.

(C) Web Age Solutions Inc. 2010

7-27

WA1503 Comprehensive AJAX

Processing the Posted XML


From a Servlet
String xml = request.getParameter("xml");
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
StringReader reader = new StringReader(xml);
InputSource inputSource = new InputSource(reader);
Document document = builder.parse(inputSource);

The example above shows how you can reconstruct the posted XML
document in the server side. First we retrieve the XML text by calling
request.getParameter. We then parse the text to create a DOM document
object.

(C) Web Age Solutions Inc. 2010

7-28

WA1503 Comprehensive AJAX

Review Questions
1.
2.

3.

4.

5.
6.

What choices exist for the application layer protocol?


What are the pros of the plain HTML snippet
approach?
What are the cons of the plain HTML snippet
approach and how are they addressed by the XML
document approach?
What does a server need to do to send back XML
data to the client?
What does a client need to do to process XML data?
What does a client need to do if they want to send
XML data to the server?

(C) Web Age Solutions Inc. 2010

7-29

WA1503 Comprehensive AJAX

Review Answers
1.

2.

Plain HTML snippets, XML document, SOAP


(web services), Direct Web Remoting (DWR),
and JSON (JavaScript Object Notation)
The pros of the plain HTML snippet approach
that it's very easy to implement.

(C) Web Age Solutions Inc. 2010

7-30

WA1503 Comprehensive AJAX

Review Answers
3.

One con of the plain HTML snippet approach is that


the look and feel gets divided between the client and
the server. The XML document approach only sends
back XML, so it's GUI neutral.
The other con is that the entire reply of the server is
set to the innerHTML property of an element, which
means you can't update different parts of the page
with pieces of data in the reply. This is a non-issue
with the XML document approach, since the DOM
document created based on the XML can be iterated
through and used to update different portions of the
page.

(C) Web Age Solutions Inc. 2010

7-31

WA1503 Comprehensive AJAX

Review Answers
4.

5.

The server needs to use an XML API, such as JAXP,


to create a DOM document that will contain the reply
data. It must set the content type to
"application/xml" or "text/xml" and serialize the DOM
document in the HTTP reply stream.
The client needs to obtain the DOM document object
that was parsed out by the request object using the
request object's responseXML property. It then
needs to use the JavaScript DOM API to iterate
through all the elements in the document to retrieve
the data and update different portions of the page.

(C) Web Age Solutions Inc. 2010

7-32

WA1503 Comprehensive AJAX

Review Answers
6.

A client needs to create a DOM document


object, serialize it, escape the XML, set the
request header to application/x-wwwform-urlencoded; charset=UTF-8, and
send the data as the body of a POST request.

(C) Web Age Solutions Inc. 2010

7-33

WA1503 Comprehensive AJAX

WA1503 Comprehensive AJAX


Communication With Server JSON

(C) Web Age Solutions Inc. 2010

8-1

WA1503 Comprehensive AJAX

Introduction

In the "basic" chapter we covered HTML and XML and formatted data
exchange.

In this chapter, we will discuss ways to implement a high level object


oriented data exchange.

Although powerful, the problem with XML is that, much code needs to be
written in client and server side to convert data into XML. For example,
when the server sends data to the client, Java objects need to be converted
to XML. Upon receiving the data, a client will need to navigate the XML
document to retrieve data.

In this approach, programmers work with native objects (Java objects in


the server side and JavaScript objects in the client side). A RPC engine in
the middle takes care of converting the objects to some kind of a data
format for network transfer.

This approach speeds up programming as the developers do not have


to write any code to prepare the data that is sent over the network.
Two options will be discussed:

JavaScript Object Notation (JSON) In this chapter.


Direct Web Remoting (DWR) In the next chapter.

(C) Web Age Solutions Inc. 2010

8-2

WA1503 Comprehensive AJAX

JavaScript Object Notation


(JSON)

JSON represents a JavaScript object as a string.

Instead of converting XML to and from a JavaScript object, it


is far easier and faster to convert a JSON string to and from
a JavaScript object.

JSON is covered by ECMAScript specification.


JSON does not have or require any separate
specification. Although all JSON related activities are
currently monitored by www.json.org.
JSON has always been there but gained fresh
popularity due to AJAX.

(C) Web Age Solutions Inc. 2010

8-3

WA1503 Comprehensive AJAX

JSON Syntax

An object is represented by:

For example, a JavaScript object:

{property1: value, property2: value }

var customer = new Object();


customer.id = 10;
customer.name = "J. Buchman";
customer.active = true;

Is represented in JSON as:

This is basically the object literal notation of JavaScript. For


example, we can also write:

{"id":10,"name":"J. Buchman","active":true}

var customer = {"id":10,"name":"J. Buchman","active":true};


alert(customer.name);

JavaScript allows you to construct a new object by using the object literal
notation. For example:
var customer = {"id":10,"name":"J. Buchman","active":true};
A JSON string is simply a string formatted in that notation. For example:
{"id":10,"name":"J. Buchman","active":true}
Such a string can be exchanged between an AJAX client and server.

(C) Web Age Solutions Inc. 2010

8-4

WA1503 Comprehensive AJAX

JSON Syntax

The name of a property is always a string. (In


JavaScript quoting of a string is optional if the
it doesn't have any white space in it).
The property value can be:

An array of objects is represented as:

A quoted string (UNICODE encoded)


A number (integer or decimal).
A boolean literal true or false.
[{object literal 1}, {object literal 2},]

See example of array below.

For example, consider a JavaScript array:


var list = new Array();
var customer;
customer = new Object();
customer.id = 10;
customer.name = "J. Buchman";
customer.active = true;
list[0] = customer;
customer = new Object();
customer.id = 11;
customer.name = "Randy Cole";
customer.active = true;
list[1] = customer;
JSON representation of the array is:
[{"id":10,"name":"J. Buchman","active":true},{"id":11,"name":"Randy Cole","active":true}]

(C) Web Age Solutions Inc. 2010

8-5

WA1503 Comprehensive AJAX

How Does JSON Based


Communication Work?

The servers response is formatted as a JSON string.


The client can easily convert that to an object:

The client can then easily access the object


properties:

var customer =
eval( "(" + replyString + ")" );

document.getElementById("name").innerHTML =
customer.name;

As you can see, this approach requires less coding


than XML transfer.
The client can also send HTTP request data as JSON.

In that case the server needs to convert the JSON string into
Java objects. JSON is used primarily with HTTP reply.

The client can send request data either as JSON string or as regular POST
data. The latter is easy and no special API is required in the server side. If the
client sends a JSON string, the server will need to use a JSON API to convert
the string into Java object.

(C) Web Age Solutions Inc. 2010

8-6

WA1503 Comprehensive AJAX

How JSON Based


Communication Work?
Ajax Code

Server Code

GET GetCustomer?id=10

{"id":10,"name":"J. Buchman","active":true}

The AJAX code in the browser sends a GET or POST request. The server
responds with a JSON string. The client code receives the JSON string and
constructs a JavaScript object by simply calling the eval() method.

(C) Web Age Solutions Inc. 2010

8-7

WA1503 Comprehensive AJAX

JSON: Server Side

In the server side, write a Servlet or JSP. This will


return data as a JSON string.
Utility libraries are available to convert Java objects
(including arrays) into JSON strings.

Download source from http://www.json.org/java/json.zip


and compile it.

The org.json.JSONObject class represents a


JavaScript object.
The org.json.JSONArray class represents a JavaScript
array.
Both classes can be created from a Java class. Both
provide a toString() method that returns a JSON
string representation of the JavaScript object.

(C) Web Age Solutions Inc. 2010

8-8

WA1503 Comprehensive AJAX

JSON: Server Side


Let us say that we wish to create a JSON string for the following
Java class:
public class Customer {
public int id;
public String name;
public boolean active;
}

All property fields must be public. Getter and setter methods are
optional.

If the property is a collection of objects, use the JSONArray


class which will be discussed shortly.

In the next slide we see how a JSON string is created for an


object of this class.

(C) Web Age Solutions Inc. 2010

8-9

WA1503 Comprehensive AJAX

JSON: Server Side


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Customer c = new Customer();
c.id = 10;
c.name = "John G. Reeves";
c.active = true;
String propList[] = {"name", "id", "active"}; //List of public field names.
JSONObject jo = new JSONObject(c, propList);
String replyData = jo.toString();
PrintWriter out = response.getWriter();
out.println(replyData);
}

The JSONObject constructor takes the Java object that needs to be


converted. It also takes an array of field names of the object's class. These
fields must be public fields.
To get the JSON string for the JSONObject, simply call its toString() method.
In this example, the servlet will return:
{"active":true,"name":"John G. Reeves","id":10}

(C) Web Age Solutions Inc. 2010

8-10

WA1503 Comprehensive AJAX

JSON: Client Side

The client converts the returned JSON text into JavaScript


object by simply evaluating it.

function fetchCustomer() {
ajaxGet("GetCustomer?id=10", showResult);
}
function showResult(request) {
var customer = eval("(" + request.responseText + ")");
document.getElementById("result").innerHTML =
customer.name;
}

Notice, how the customer object has the same fields as the corresponding
Java class.

(C) Web Age Solutions Inc. 2010

8-11

WA1503 Comprehensive AJAX

Working With Arrays

To return an array objects from a Servlet, use


the JSONArray object.

A JSONArray object contains a list of JSONObject


objects.
See example below.

A JSONArray object is constructed as follows:

JSONArray ja = new JSONArray(Collection list);


Where, list is a Collection of JSONObjects. For
example, it can be an ArrayList as used below.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
String propList[] = {"name", "id", "active"};
Customer c = null;
ArrayList list = new ArrayList();
c = new Customer();
c.id = 10;
c.name = "John G. Reeves";
c.active = true;
list.add(new JSONObject(c, propList));
c = new Customer();
c.id = 11;
c.name = "Baily J. James";
c.active = false;
list.add(new JSONObject(c, propList));
JSONArray jsonList = new JSONArray(list);
String replyData = jsonList.toString();
PrintWriter out = response.getWriter();
out.println(replyData);
}

(C) Web Age Solutions Inc. 2010

8-12

WA1503 Comprehensive AJAX

Working With Arrays


The client receives an array of objects.
function getCustomerList() {
ajaxGet("FetchAllCustomers", showResult);
}

function showResult(request, data) {


var list = eval("(" + request.responseText + ")");
for (var i = 0; i < list.length; ++i) {
var customer = list[i];
alert(customer.name);
}
}

Once again, we evaluate the JSON string returned by the server. This time,
the evaluated object is an array.

(C) Web Age Solutions Inc. 2010

8-13

WA1503 Comprehensive AJAX

Advanced JSONObject
Methods

JSONObject(Map propertyList) Constructor that


initializes the JSONObject with properties from a
map.
put(String propertyName, Object value) Adds a
new property. The value should be another
JSONObject or String.

For exampe, when a Customer class has an Address class


field.

put(String propertyName, int value) Adds a new int


property
put(String propertyName, Collection list) Adds a
collection of JSONObject objects.

For example, when a Customer class maintains a collection


of Address objects.

Previously, we have learned how to construct a JSONObject from a Java


object. Here we learn how to add additional properties to the JSONObject. For
example:
JSONObject obj = new JSONObject();
obj.put("name", "Jack D.");
obj.put("id", 10);

(C) Web Age Solutions Inc. 2010

8-14

WA1503 Comprehensive AJAX

Advanced JSONArray Methods

put(int value) Append an integer value to


the array.
put(Map propertyList) Append a new object
with properties listed in a Map.
put(Object o) Append a new JSONObject or
a String.
For all of the above methods, you can also
specify an index where the value will be
added.

put(int index, Object o)

Example:
JSONArray arr = new JSONArray();
HashMap map = new HashMap();
map.put("name", "Jack D.");
map.put("ID", new Integer(10));
arr.put(map);
map.put("name", "Mary M.");
map.put("ID", new Integer(11));
arr.put(map);
//Generate the JSONString
String jsonStr = arr.toString();
Now jsnStr will be:
[{"name":"Jack D.","ID":10},{"name":"Mary M.","ID":11}]

(C) Web Age Solutions Inc. 2010

8-15

WA1503 Comprehensive AJAX

Summary

JSON requires less code than XML.


The browser can easily convert a JSON string to a
JavaScript object by simply calling the eval()
function.
The server side code can generate a JSON string
from a Java object using a simple API.
Downsides:

Server side code is almost as much as XML.


No way to invoke a function in the server (RPC style). We
will need to write a Servlet for every task.

Later, we will see how Direct Web Remoting solves


these problems.

(C) Web Age Solutions Inc. 2010

8-16

WA1503 Comprehensive AJAX

Review Questions
1.
2.

3.

4.

5.

6.

What is JSON?
How can you produce JSON using Java on the server
side?
When constructing a JSONObject, what 2
parameters must be supplied to the constructor?
When creating a model class using Java, what
restriction is placed on its fields?
How does the client convert a JSON string returned
by the server into a JavaScript object?
What is the advantage of the JSON approach over
the XML document approach?

(C) Web Age Solutions Inc. 2010

8-17

WA1503 Comprehensive AJAX

Review Answers
1.

2.

3.

4.

JSON is a way of representing a JavaScript


object using a string. An object is
represented by {property1: value,
property2: value, }.
You can either manually create JSON syntax
yourself or use a utility library, such as the
one from www.json.org, to convert Java
objects (including arrays) into JSON strings.
The Java object and an array of the public
field names of the Java object.
The Java object's fields must be public

(C) Web Age Solutions Inc. 2010

8-18

WA1503 Comprehensive AJAX

Review Answers
5.
6.

It uses the eval function.


The client doesn't need to convert XML to
and from a JavaScript object. It can easily
convert a JSON string to and from a
JavaScript object.

(C) Web Age Solutions Inc. 2010

8-19

También podría gustarte