Figure DOM and HTML page

spongereasonInternet and Web Development

Nov 12, 2013 (3 years and 6 months ago)

120 views

As seen in the previous chapter, Ajax makes a
n

XMLHttpRequest

to server first, and then
the
server process
es

the request and send
s

the response back to JavaScript client. The response is in

XML format at most of time. The JavaScript in the client page wil
l parse the XML respo
nse and
update the related

HTML elements in the current page without refresh
ing

the entire whole page.
The left block in Fig. 6.1 is the current HTML page which issues the Ajax request.
When this
page is browsed by a

web browser, the p
age is translated from the text to an object model
. All the

browser
s

actually work

directly with the Document Object Model
(DOM), and

a
ll HTML tag and
CSS
tag elements are incorporated into the

DOM as element nodes.

The changes to the page’s
DOM result in
the changes of the page presentation.

After
the browser’s
JavaS
cript interpreter parsing

the XML respon
se, JavaScript code will update

the DOM elements (or add new element nodes, or remove or modify existing element no
des)
which always point to

HTML
page
tag
s
. The entire HTML page is
referenced as
a DOM
document
which is
built up like a tree. If JavaScript changes any DOM element,
the change
immediately appears i
n the corresponding element on the HTML page. Some portion in the
HTML pag
e in Fig 6.1 is upda
ted but the remaining

portion is unchanged. If the page is a huge
map or table Ajax

can save huge time for reloading

the whole page.

This chapter
focuses on how Ajax handles the server response. Server may respond Ajax request
in the
response
formats of te
xt, HTML, XML, JSON, and others. You will learn how Ajax
JavaScript parse
s

and evaluate
s

the responses an
d update the HTML DOM for

the current page.

The hands
-
on examples for Ajax

parsing of
different type responses are also demonstrated in this
chapter.





Figure DOM and HTML page


The response to the Ajax request can come in many different forms, such as XML, plain text,
(X)HTML, or JavaScript Object Notation (JSON). Depending on the data format that server
responds, there
are two different ways for JavaSc
ript

to handle it: with
responseText

or with
responseXML
. The
responseText

method is used for all formats that are not based on
DOM element

updated

DOM elements unchanged

Event


handle

Server

JavaScript

Response

p
arsing

XMLHttpReques
t

Response

Current HTML Page

XML. It returns an exact representation of the response as a string

text
. Plain text,
HTML, and

JSON are such

formats that use
responseText
. For example,



document.getElementById(’body’).innerHTML = req.responseText;



simply sets

the body element

of the current HTML page

with the

contents of
responseText

. The
responseText
is always returned, b
ut
responseXML

is only returned when the response type is
text/XML
.

The following sections will give detailed discussions on the response parsing by Ajax JavaScript
code.


DOM



1 DOM Overview


XML documents are simply

a
text that can be created and main
tained with any common text
editor. Other popular data storage formats are binary and proprietary to a specific vendor such
that you need special programs to view and edit the data (
e.g.
, Microsoft Word and Excel). Since
XML is non
-
proprietary, text
-
based,

and designed for easy processing by computer software,
without much effort, you can create your own application to read and manipulate XML
documents. However, many programs for processing XML are freely available, so you don’t
actually have to write your
own. The software programs that know how to read and manipulate
XML documents are commonly called
XML parsers
. XML parsers read the XML data into
computer memory and give you either specific pieces of the data that you are looking for, or the
whole XML doc
ument.

The most popular XML parser APIs today are the Simple API for XML (SAX) and the Document
Object Model (DOM). The first
official

version of DOM, labeled DOM Level 1, was developed
by the World Wide Web Consortium (W3C) and released in October of 1998
. DOM Level 1 is
based on the first
unofficial

version of DOM, labeled DOM Level 0, which was used in the
Netscape Navigator 3.0 and Internet Explorer 3.0 browsers. Netscape originally developed “DOM
Level 0” as a programmatic interface to HTML that was im
plemented in JavaScript
(http://www.mozilla.org/js/) and first packaged with the Netscape Navigator 2.0 browser in
October of 1995. Now, the official DOM specification provides a programmatic interface to both
HTML and XML. DOM parses the entire XML docume
nt into memory as a hierarchical object
model


a tree structure of objects called
nodes
. All the tags and the text data they contain are
encapsulated by node objects that can be randomly referenced multiple times until you explicitly
remove the tree struc
ture from memory. DOM provides the benefit of being able to randomly
access the parsed document. Only XML DOM is introduced in this book because DOM parsing is
widely used in JavaScript and Ajax

DOM is a tree
-
based model that is developed and maintained b
y the World Wide Web
Consortium (W3C).
In
DOM, the entire XML document is parsed and cached in memory as a tree
structure of objects called
nodes
. You cannot access any part of the object model until the entire
document is parsed.


JavaScript API provides
DOM parser.

DOM provides an object model for both HTML and XML documents that is platform and
language independent. DOM has been implemented in many languages including Java,
JavaScript, C++, Perl, and Python. The original DOM, referred to as DOM Level 0,
was
implemented in JavaScript. At that time, the DOM was only meant to provide a programmatic
interface to HTML so that Web developers could write scripts that dynamically manipulate the
content of a Web page (commonly referred to as DHTML


the D is for “
dynamic”). Since the
different browsers used their own versions of DOM, Web developers were burdened with needing
to add control logic (if statements) that branched their scripting code for every possible
peculiarity of every possible Web browser that may
access their Web site. Otherwise their
dynamic Web content might not work for some viewers. To resolve this problem, the W3C
developed a new version of DOM, called DOM Level 1, which was intended as a standard API
for all browser implementations (Netscape,

Mozilla, Internet Explorer, Opera, etc.), as well as
any other applications that used a programmatic interface to HTML or XML documents. The
standard API has allowed Web developers to mostly eliminate the messy branching in their
scripting code and still
provide dynamic Web content that is cross
-
browser compatible. I say
“mostly” because there are still quirky differences between the browsers that require special
handling to make the script code cross
-
browser compatible.

The latest version of the document
object model is DOM Level 3. Level 3 was released by the
W3C as a Recommendation in April of 2004 and is available on the Web at
http://www.w3.org/TR/DOM
-
Level
-
3
-
Core/. The most popular version of the DOM in use today
is DOM Level 2, which was released by
the W3C as a Recommendation in November of 2000
and is available on the Web at http://www.w3.org/TR/DOM
-
Level
-
2
-
Core/. Links to all of the
DOM specifications can be found at http://www.w3.org/DOM/DOMTR. Since most browsers
and parsers support DOM Level 2,
that is the version we will discuss in this chapter.

An illustration of the DOM Level 2 c
lass hierarchy is given in F
igure
6.2
below.



Comment
Node
Document
Element
CharacterData
Text
Attr
DOM 2 Interface
DOM 2 Class
java.lang Class
DocumentFragment
EntityReference
Entity
DocumentType
Notation
CDATASection
DOMImplementation
NodeList
NamedNodeMap
ProcessingInstruction
DOMException
RuntimeException
package org.w3c.dom


DOM Level 2 Classes (package org.w3c.dom)


2 DOM
Nodes


A
DOM
node is a basic object type
in the DOM. In above diagram you can see that every thing
defined by

the DOM extends the
node

class
. A XML document is
organized in

a tree of nodes. A
HTML document is also a DOM tree where the root element node is the HTML tag node. The
document

node repr
esents the DOM tree, i.e.

the whole document. Every element is a node in the
DOM tree. Every attribute is a node. Every text string is a node. Each node has a parent node
except the top
-
most (root) node. Each node may have its sibling nodes as well. For
example, in a
HTML document the
body

and
head
nodes

have the
ir common parent
html

root node. Each
element node in a DOM tree has a
parent
; that parent is either the child of another element, or is
the top
-
most element in the DOM tree.

There are many way
s to navigate a DOM tree. You can ei
ther start from the root node and

then
navigate the DOM tree step by step
to scan all

node
s

in the tree
or directly
find a node by its id or
name.

The
getElementByTagName()

method can be used to find
element
nodes by ele
ment name. For
example,
myDocument.

getElementByTagName(“body”)

references to the body tag elem
ent in a

HTML page if
myDocument

variable is assigned to
the
document
.

The
getElementByTagName()

actually returns a node list(array in JavaScript) because ther
e may be many nodes having the
same name. If there is only one matched node, it still returns a list
but
with a single node in it.
That’s why you need to
use
getElementByTagName()[0]

to
access that single element
.

The other
direct element access
method
is
call
ed

getElementById()

which
can be used to access
an element
node
with its id if the searched element has an id attribute

assigned
.

After locating a specific element you can navigate its neighbor nodes nearby in the DOM tree.
The navigation methods are

introduced in the next few sections.

Each
HTML

element has an
innerHTML

property that defines the text that occurs
between that element's opening

and closing tag. For example, t
he follow
ing

JavaScript
fragment will change the text of “old” in
bold

to the
text of “new” in
bold

by accessing
the
innerHTML

property of
the
bold

element with id of “myId”.



function update(){


document.getElementById('myId').innerHTML = 'new';

}

</script>

<body><p>Hello World <b id='myId'>old</b> </p>

<input type='button' oncli
ck='update()' value='update Text'/>

</body>


2.1 Node Types


The most important DOM node types are
document

node,
element

node,
attribute

node,
and
text

node,




document

node

represents curent

HTML document.


The
document
node is actually not an
element in an HTML (or XML) page, but the page



itself. So in an HTML Web page, the document node is the entire DOM tree

for the page
.



element
nodes

represent HTML elements like
head

or
body
.



attribute
nodes

represent the attributes on HTML ele
ments, like
href

(of

the
a

element) or
src

(of

the
img

element).



text

nodes

represent text in the HTML document, like "press me” This is the text that
appears inside elements like
h1

or

p
.


In some cases, you'
ll need to figure out what type node you meet

before you can process it.
When you're navigating through a DOM tree you might not know whether you've moved to
an
element

or
text
. It's easy

to figure this out

by checking node type constants
. The DOM
node type defines several constants, like this:




Node
.
DOCUMENT_NODE is the constant for the document node type
.



Node.
ELEMENT_NODE is the constant for the element node type.




Node.
ATTRIBUTE_NODE is the constant for the attribute node type.



Node.
TEXT_NODE is the constant for the text node type.


The
NodeType

pr
operty

(
introduced in
next section) of a node can be used to check above node
type constant.


6.2.2.2

Node Properties


DOM supports e
lement type and text type nodes. Each DOM node has its properties just like each
object has its properties. The key proper
ties of a DOM node are:




nodeType returns the type of node.



nodeName is the name of the node. It returns null for
text

node as
text

nodes don't have a
name.



nodeValue is the "value" of the node. It returns the text for the
text

node and
the
attribute
for
a
ttribute

node
,

but the value of an element's
nodeValue

property is always null
.


attribute is only used for
element

node; it returns a list of an
element
's attributes like ‘id’


attribute of element node.



parentNode returns the node's parent. Ev
ery
element

node,
attribute

node, and
text

node
has a parent node in DOM tree.



childNodes is a list of a node's children. An
y

element

has its
childNode
s in HTML page
document but
text
nodes and
attribute

nodes don't have any children.



firstChild points to
the first node in the
childNodes

list.



lastChild points to the last node in the
childNodes

list.



previousSibling returns the node that precedes the current one in this node's parent's
childNodes

list



nextSibling is similar to the
previousSibling

property;
it
re
turns the next node in the
parent's
childNodes

list.

You can use the
nodeType

property to compare a node
type constants to identify the type of a
node. Here is a simple example.

var someNode = document.getElementById(“myId”);

if (someNode.
nodeType ==

Node.ELEMENT_NODE)


alert("The element name is

" + someNode.nodeName);

else if (someNo
de.nodeType == Node.TEXT_NODE)


aler
t("The text in the text node is

" + someNode.nodeValue);

else if (someNode.no
deType == Node.ATTRIBUTE_NODE)


alert("The attribute
name is

" + someNode.nodeName


+ " and value is

'" + someNode.nodeValue + "'");


After you know the DOM nodes, you need to know how DOM organizes all nodes in a hierarchy
tree. Here is a simple HTML page. What the web browser sees is a DOM tr
ee which is shown in
Figure 6.3.



<html>


<head><title>XHTML Test</title></head>


<body>


<h1>Heading Content</h1>


<p>First Paragraph Content</p>


<p id=
"
p2
"
>Second Paragraph Content</p>


</body>

</html>


In the DOM tree you can find that
each tag has a node in the tree. The root node of tree is the
HTML tag. In order to reference the root node in the tree, the document node must be referenced.
Attr
node is not a child node of any other node. It associates with the node it describes.


Document
Element
html
Element
head
Element
title
Element
body
Element
p
Element
p
Element
h
1
Text
XHTML Test
Text
Heading Content
Text
First Paragraph Content
Text
Second Paragraph Content
Attr
id
=
”p
2


.

Figure 6.3 DOM tree


Based on this DOM tree of the HTML page above, you can use JavaScript to traverse the tree to
ac
cess any node in the tree, i.e.

to access any tag element in the HTML page.

The following code
shows how to ech
o HTML element,
head

element, and
title

content.


//

Gets a reference to the root node <html> of the html document

in DOM tree


var htmlElement = document.documentElement;



// <html>

element


alert("The page root element is " + htmlElement.nodeNa
me);



// <head> element


var headElement = htmlElement.getElementsByTagName("head")[0];




alert(headElement.nodeName);



// <title> element


var titleElement = headElement.getElementsByTagName("title")[0];


var titleText = title
Element.firstChild;


alert("The page title is '" + titleText.nodeValue + "'");




// <body>


var bodyElement = headElement.nextSibling;




// ...

}

2.3 Node Manipulation Methods


Most of node methods process the children of a node
. That's their primary purpose. If you want

to

process the node itself, you can simply use the properties of a node.
Here o
nly
the
HTML DOM
operation related methods are listed

below.



appendChild(new
)
adds a new child node to the end of the list of
childr
en of a node




hasChildNodes() returns true

if a node has any child nodes,
otherwise it returns false



insertBefore(new, reference
) inserts the new

c
hild node before
the reference

n
ode.



replaceChild(new, old
) replaces the old

c
hild node with the new

Child n
ode.



removeChild(old
) removes the old

c
hild node from the node the
function is run on.



hasAttributes() returns true

if a node has any attributes,
otherwise it returns false



cloneNode() clones this node.

You can also use the
document

object to create new n
odes such as element node, text

node, and
attribute node using the following listed methods:



createElement(elementName) creates an element with the supplied
name.



createTextNode(text) creates a new text node with the supplied
text.



createAttribute(attribut
eName) creates a new attribute with the
supplied name.

After you create new

nodes by these methods, you must attach them
to the existing

nodes or
insert th
em into any particular document,

insertBefore()

or
appendChild()

are these methods
listed before. Her
e is a
n

example code to show you how to
create a text node for “My Title” and
attach it to a title element, and then attach the title element to an existing head element in a
HTML DOM.

var tElement = myDocument.createElement("title");

var text = myDocument
.createTextNode("
My Title
");

t
Element.appendChild(text);

headElement.appendChild(t
Element);

2.3.1 Methods for
Attribute nodes

Next, let’s discuss how to work with node attributes.

Here is the list of
Methods that work

with attributes:



getAttribute(name)
ret
urns the value of the named attribute
.



removeAttribute(n
ame) removes the named attribute
.



setAttribute(name, new
)
creates an attribute

and sets its value to
new
value.



getAttributeNode(name)
returns the named attribute node.




nameremoveAttributeNode(nod
e) removes the attribute node
.


Let’s use these methods to set attribute for an
img

element. In the code below, the JavaScript
creates a new
img

element, sets up some attribut
es, and then attaches it to an

existing
element in a
page.


var imgElement = docu
ment.createElement("img");

imgElement.setAttr
ibute("src", "www.image.com/myImage
.jpg");

imgElement.setAttribute("width", "1
0
0");

imgEl
ement.setAttribute("height", "10
0");

some
Element.appendChild(imgElement);

Here
src
,
width
, and
height

are all attributes
of
img

element in the HTML DOM. The DOM
represents attributes by

nodes, and you can always get a
n element's attributes using its

at
tributes
property
, as shown here:

// Print attribute information of a

element

Var msg =
"
"
;



var atts = imgElement.att
ributes;


for (i
=0
; i<atts.length; i
++) {


var att = atts.item(i
);


msg = msg + ",

" + att.nodeName + ": '" + att.nodeValue + "'";


}


alert(msg);


2.3.2 Methods for
Text nodes

The
nodeValue

property is commonly used to ge
t the text from a text node as follows
:

var p
ara
Elements = bodyElement.getElementsByTagName("p");

for (i=0; i<pElements.length; i++) {


var pElement = pElements.item(i);


var t = pElement.firstChild.nodeValue;


alert(t);}

This script prints all text con
tents of all
<p>

tags in
body

element of a
html

page by
nodeValue

property of text nodes of
pElement
..

There are few methods specific for

text nodes. They

deal with adding to or splitting the data in a
node:



appendData(text) adds a string text to the end

of the text node's current text.



insertData(position, text) inserts string text at the given position of the text node.



deleteData(offset, n) removes n characters from the text node starting at offset.



replaceData(position, n, text) removes n

characters
at

the position indicated, and inserts
the new text t
o the

place of the removed text.

The following

two examples give you some ideas about the DOM tree manipulation. First
examp
le simply navigates an

HTML web page
.


<html>


<head><title>DOM

Test</title>



<
script language="JavaScript">


function scan() {




var htmlElement = document.documentElement;


var headElement = htmlElement.getElementsByTagName("head")[0];


if (headElement != null) {


alert( headElement.nodeName);


var titleEle
ment = headElement.getElementsByTagName("title")[0];


if (titleElement != null) {




var titleText = titleElement.firstChild;


alert("The
title is '" + titleText.nodeValue + "'");



// look for <body> element with nextSibling of h
eadElement, print all


//text contents in "p
"

tags



var bodyElement = headElement.nextSibling;


var pElements = bodyElement.getElementsByTagName("p");


for (i=0; i<pElements.length; i++) {




var pElement = pElements.item
(i);


var t = pElement.firstChild.nodeValue;


alert(t);}



}


}


}

</script>

</head>

<body>


<h1>Heading Content</h1>


<p>First Paragraph Content</
p>

<p id=”p2”>Second
Paragraph

Content</p>

<a href="#" onClick=”scan();” >click on me to navigate the DOM</a>

</body>

</html>


The following screen sh
o
ts show the DOM manipulations after you clicked on the link
button.






Example 2: find and remove f
irst or all
the
child

elements

in
an element in the

HTML
page

above
:

// look for <body> element by getElementsByTagName("body
")[0];

// Remove <p> elements in the bodyElement


var bodyElement = html
Element.
getElementByTagName(“body”);


var pElemen
ts = bodyElement.getElementsByTagName("p");


var curren
tNode = pElements.childNodes[0
];


if (cu
rrentNode.nodeName == "p")


pElements.removeChild(currentNode);

You can also use
getElementsByTagName()

to find the first
<p>

eleme
nt and remove it as
follows.

// Re
move first <p> element

in the body


var pElements = body
Eleme
nt.getElementsByTagName("p");


var

pElement = pElements.item(0)
;


bodyElement.removeChild(p
Element);



If there are multiple
<p> element
s in the
b
ody
Elemen
t you can use loop to iterate the node

list
returned by
getElementsByTagName()

and remove all <p>

nodes one at a time


var pElements = body
E
lement.getElementsByTagName("p
");



for (i=0; i<p
Elements.length; i++) {


var

pElement = pEleme
nts.item(i)
;


body
Ele
ment.removeChild(p
Element);


}

So far you have already seen the DOM structure and known how a XML document or HTML
document is organized in the DOM. You also know how to parse the DOM tree; how to navigate
the DOM tree; ho
w to create new nodes and append them to existing child lists; how to remove
nodes; how to update or replace an existing
node.

Whenever you update the page DOM, the page
is updated immediately. That is why Ajax can partially update a page without reloading

and
refreshing the whole page.


Examples and Lab Practice


Lab1: Ajax wi
th p
lain text response


You will practice with Ajax request on plain text response. Here is a
student.txt

file with three student
records as follows.


John

cse

3.6


Peter

ec

3.8


Si
va

cse

3.3


The following is the Ajax request enclosed in the
txtTest.html
.


<HTML>

<head>

<script type="text/javascript">


var req;


function ajaxCall() {


var url = "student.txt";

if (window.XMLHttpRequest) {


req = new XMLHttpRequest();


} el
se if (window.ActiveXObject) {


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


}


req.open("GET", url, true);


req.onreadystatechange = callback;


req.send("");

}


function callback() {


if(req.readyState == 4){


document.getElementByI
d('display').innerHTML = req.responseText;


}

}


</script>

</head>

<body onLoad='ajaxCall();'>

<div id="display"></div>

</body>

</html>


When this page is loaded the
ajaxCall()

function is invoked by
onLoad='ajaxCall();
'
.
The function


ajaxCall()

will m
ake an Ajax request to an URL which points to the
student.txt
. The
callback()

function is
called back when the
responseText

response returns and inserts the
responseText

contents into the
div

of
display

in the web page itself as follows.




Lab2:

Ajax wit
h
XML

response



You will practice with Ajax request on XML response. Here is a
student.
xml

file with three student records
as follows.


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

<students>



<student>



<name>John</name>


<major>cse</major>



<gpa>3.6</gpa>


</student>


<student>



<name>Peter</name>


<major>ec</major>


<gpa>3.8</gpa>


</student>


<student>



<name>Siva</name>


<major>cse</major>


<gpa>3.3</gpa>


</student>

</students
>


The Ajax request program with XML response is given in the following
xmlTest.
jsp
:


<HTML>

<head>

<script type="text/javascript">

var req;


function ajaxCall() {


var url = "student.xml";



if (window.XMLHttpRequest) {


req = new XMLHttpReques
t();


} else if (window.ActiveXObject) {


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


}



req.open("GET", url, true);


req.onreadystatechange = callback;


req.send("");

}


function callback() {


if (req.readyState == 4) {



parseMessage();




}

}

function parseMessage() {


var students = req.responseXML.getElementsByTagName('student');


for (var i=0;i<students.length;i++)


{



var ne = document.createElement('div');



ne.className = 'student';



var

b = document.createElement('b');



b.appendChild(document.createTextNode(students[i].getElementsByTa
gName('name')[0].firstChild.nodeValue));



ne.appendChild(b);



var p = document.createElement('p');



p.appendChild(document.createTextNode(students[i].ge
tElementsByTa
gName('major')[0].firstChild.nodeValue));



ne.appendChild(p);


var i1 = document.createElement('i');



i1.appendChild(document.createTextNode(students[i].getElementsByT
agName('gpa')[0].firstChild.nodeValue));



ne.appendChild(i1);


document.getElementById('display').appendChild(ne);



}

}

</script>


</head>

<body onLoad='ajaxCall();'>

<div id="display"></div>

</body>

</html>

You will find that this script is almost identical to the one in lab 2 except the
reponseXML

is

used instead of
responseText
.

The first line in
parseMessage()
:



var students = req.responseXML.getElementsByTagName('student');


uses
getElementsByTagName()


to get all three
student

elements and puts them in a node list array called
students
.

After tha
t, the XML handling iteration is same as the previous JSON handling iteration. Notice the way to
access the
name
,
major
, and
gpa

of each student by XML DOM manipulation notations such as
students[i].getElementsByTagName('name')[0].firstChild.nodeValue),

students[i].getElementsByTagName('name')[0].firstChild.nodeValue), and
students[i].getElementsByTagName('name')[0].firstChild.nodeValue).


The output page is same as the output page in lab 2.




Lab 3 Ajax Request with Response from PHP Web Sever


In thi
s lab you will know how to send a Ajax request by
req.send(arg)
, where
req

is an
XMLHttpRequest

object and
arg

argument includes pairs of name/value, to a
php

web server page
and how Ajax handles the response returned and dynamically update
s

the table DOM

based on
the response. You can find the installation and configuration of various open source web servers
and PHP web server pages in the appendix of this book.

This example shows a student table with columns

of student id and his/her name.

The table is
b
lank at beginning. Users can fill in student name in the input text box and click the
Add

button; a
Ajax request will take these data as arguments and send
them
to the
php

server page for some

processing such as verification. In this simple example, the
ph
p

server page simply send
s

the data
back to the client in the
responseText

without any handling. Once Ajax verifies the request status,
it locates the
table

node by its id(“display”) in the DOM first. Then it constructs a new
TR

row
node with two child
TD

nodes (id, name) and attaches the new
TR

node into the table node in

the

DOM to update the display.

The Ajax code and
H
TML form is given in the
Tabledisplay.html.


<Html>


<Head>


<script type="text/javascript">


var req, i=0;



function ajaxCall()


{


var poststr = "username=" + encodeURI(document.frmTest.content.value);


var url = "ajax.php";


if (window.XMLHttpRequest) {


req = new XMLHttpRequest
();


} else if (window.ActiveXObject) {


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


}


req.open("POST", url, true);


req.onreadystatechange = callback;


req.s
etRequestHeader("Content
-
Type", "application/x
-
www
-
form
-
urlencoded");


req.setRequestHeader("Content
-
length", poststr.length);


req.send(poststr);


}


function callback() {


if (req.readySt
ate == 4) {


if (req.status == 200) {


// update the HTML DOM if message is valid


ajax_update('display', req.responseText);


}


}


}


function ajax_update(table,name)


{


var tb= document.getElementById(table);


var tr= document.createElement('TR');


tb.appendChild(tr);


i++;


var td1= document.createE
lement('TD');


tr.appendChild(td1);


td1.innerHTML= '00'+i;


var td2= document.createElement('TD');


tr.appendChild(td2);


td2.innerHTML= name;


}


</script>


<
body>


Register:


<form action="" name="frmTest" method="post">


<input type="button" id="button1" onclick="javascript:ajaxCall();"
value="Add"/>


<input type="text" name="content" />


</form>


<table id="d
isplay" border="1">


<tr><td>No</td><td>Student Name</td></tr>


</table>


</body>

</html>

This example uses the POST me
thod to send the request because the form posting requires POST
method in Ajax request.

The line of


var poststr = "
username=" + encodeURI(document.frmTest.content.value);


wraps the
“username=<input name>”

in string variable
poststr

which is sent out by


req.send(poststr);



and
<input name>

comes from
document.frmtest.content.value
.(here
the

document

is the page
its
elf;
the
frmTest

is the name of the form;
the
content

is the name of the input box in the form;
the
value

is the user input)


After Ajax gets the
responseText

back from the server, it calls

the function


ajax_update('display',

req.responseText);


to update

the DOM of the table
“display

.



The

php

web s
e
r
ver page is given in
the
a
jax.php

as follows
:


<?php

$content = $_POST['username'];

echo $content;

?>


This page simply returns the value of
username

coming with the Ajax request to the
reponseText

by
thi
s line:


echo $content;


The following is the screen shot of
the
form html starting page
.

Reminder: Use Firefox brows
er.




The next screen shot shows the updated table after 4 consecutive Ajax requests were sent
the

Ajax.php
.