The Ajax program Example 18.11 makes a request to the server to get the XML file.. The server returns an XML object, and the rest of the program uses DOM methods and properties to parse
Trang 118.4.2 Using Ajax to Retrieve XML from a File
XML is the Extensible Markup Language Although similar in structure to HTML, XML
was designed to transport and store data, whereas HTML was designed to describe the
lay-out and looks of the data With XML you create markup that defines the structure of a
doc-ument, but instead of having predefined tags as with HTML, you make your own The
XML tree looks similar to the HTML upside-down document tree, starting with a root
ele-ment at the top and branching down to parents, attributes, children, and so on XML has
rules, very XML-specific syntax rules on how to create a “well-formed” document It is not
hard to learn, but if you are unfamiliar with XML, go to the W3C schools Web site where
you will find an excellent tutorial at http://www.w3schools.com/xml/xml_tree.asp.
XML data is often stored in external files as plain text The data in the XML files can be
easily exchanged between different programs, applications, and computers In this chapter
we are using Ajax to exchange data between a client and server In the previous example
the server returned a string of text from a simple text file In this example we will use Ajax
to get data from an XML file as an object and use the XML DOM to parse and display the
data And finally, at the end of this chapter, we will use an easier technology, called JSON,
to make exchanging and parsing data a little simpler In fact JSON is said to be rapidly
replacing XML because of its easy lightweight data-interchange format
The XML file for the following example, called “bookstore.xml”, is found in Example
18.10.3 If you are not familiar with XML, this file is a good example of how the markup
is structured The Ajax program (Example 18.11) makes a request to the server to get
the XML file The server returns an XML object, and the rest of the program uses DOM
methods and properties to parse out the data from the XML object and to create the
ele-ments and text nodes that will be placed in an HTML div container
Figure 18.14 A text file is retrieved and it contents displayed in a div container.
Trang 2The XML File (bookstore.xml)
Ajax Program
E X A M P L E 1 8 1 0
<bookstore>
<book category="COOKING">
<title>The Art of Simple Food</title>
<author>Alice Waters</author>
<published>2007</published>
<price>35.00</price>
</book>
<book category="AUTOBIOGRAPHY">
<title>Moments of Being</title>
<author>Virginia Woolf</author>
<published>1985</published>
<price>14.00</price>
</book>
<book category="FICTION">
<title>Plain Truth</title>
<author>Judy Picoult</author>
<published>2000</published>
<price>15.00</price>
</book>
</bookstore>
E X A M P L E 1 8 1 1
<html>
<head><title>Reading from an XML file</title>
<script type="text/javascript" src="ajaxCreateRequest.js">
</script>
<script type="text/javascript">
1 function makeRequest(url){
var httpRequest=createRequest(); /* Cross-browser check;
Get a new XMLHttpRequest object */
if( httpRequest != false){ // If we got back a request
// object httpRequest.open('GET', url, true);
httpRequest.setRequestHeader('If-Modified-Since',
'Sat, 03 Jan 2010 00:00:00GMT');
httpRequest.send(null);
httpRequest.onreadystatechange = function() {
} else{ alert("There was a problem with your request.");}
} // End createRequest function
Continues
Trang 33 function getXMLContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
4 var xml = httpRequest.responseXML;
5 var booklist = xml.getElementsByTagName("book");
6 for( j=0; j < booklist.length; j++){
var book=booklist[j];
7 var category=book.getAttribute("category");
for(i=0;i<book.childNodes.length; i++){
case "title":
title=book.childNodes[i].firstChild.nodeValue;
case "author":
author=book.childNodes[i].firstChild.nodeValue;
case "price":
price=book.childNodes[i].firstChild.nodeValue;
case "published":
published=book.childNodes[i].firstChild.nodeValue;
} } //End inner for loop
9 var para=document.createElement("p");
var brtag1=document.createElement("br");
var brtag2=document.createElement("br") var brtag3=document.createElement("br")
10 var categoryTxt=document.createTextNode("Category:
"+category);
var titleTxt=document.createTextNode("Title: " + title);
var authorTxt=document.createTextNode("Author: "+author);
var priceTxt=document.createTextNode("Price: "+ price);
11 para.appendChild(categoryTxt);
para.appendChild(brtag1);
para.appendChild(titleTxt);
para.appendChild(brtag2);
para.appendChild(authorTxt);
para.appendChild(brtag3);
para.appendChild(priceTxt);
12 document.getElementById('data').appendChild(para);
} }else { alert('There was a problem with the request.');}
}
}
</script>
</head>
E X A M P L E 1 8 1 1 (C O N T I N U E D)
Trang 4<body>
<span style="cursor: pointer; text-decoration: underline"
13 onclick="makeRequest('http://localhost/bookstore.xml')">
Get book details
</span>
14 <div id=data>
</div>
</body>
</html>
E X P L A N A T I O N
1 This function creates the XMLHttpRequest object, initializes it with the GET
meth-od and the XML file, called “bookstore.xml”, sends the request to the server, and
calls the getXMLContents() function when the state of the server changes to 4
(complete)
2 This function takes the XMLHttpRequest object as its argument It is called when
the onreadystatechange event handler is notified that the server’s readyState has
changed
3 This function checks when the server has completed the request and fetches the
contents of the XML file
4 The httpRequest.responseXML property contains the data returned from the XML file
as an XML document object.
5 The getElementsByTagName() method gets a reference to all the <book> tags stored
as an array in the XML object Look at “bookstore.xml” to see the structure
6 The outer for loop will iterate through each book in the array of books, called
booklist.
7 The XML DOM getAttribute() method returns the value of an attribute by its
name, which is “category”
8 For the name of each book, childNodes[i].nodeName, the switch statement will use
the nodeValue property to get the text for the title, author, and so on.
9 Using the DOM, elements are created that will be inserted in the div container on
line 14 A paragraph (p) and break (br) elements are created to hold the book values.
10 Next, the textNodes are created that will be appended to the paragraph.
11 Once all the text nodes are created, they are appended to the paragraph with break
tags after each line of text
12 Now, the new paragraph, built entirely with DOM methods, is inserted into the
div container defined on line 14
13 When the user clicks the underlined text, defined by the <span> tag, the Ajax
pro-gram is launched
14 This is the <div> container that will display the output from the XML file returned
from the server See Figure 18.15
E X A M P L E 1 8 1 1 (C O N T I N U E D)
Trang 518.4.3 Ajax and Forms
There are several reasons why you might choose to use Ajax for forms in your Web page
1 Faster validation
2 Auto-completing the form fields
3 Spell checking in real time
4 Updating content (weather updates, auctions, stock tickers)
5 Dynamically updating a list based on user input
When creating non-Ajax HTML forms, the <form> tag takes an ACTION attribute and
a METHOD attribute The ACTION attribute is used to specify the URL of a server-side
program that will deal with form input after the submit button is clicked, and the
METHOD attribute determines how the input will be sent, either with the HTTP GET
or POST methods In the traditional HTML form, the form will have a submit button
that, when clicked, causes the browser to bundle up the input data into a URI encoded
query string consisting of name/value pairs This encoded data will be sent to the
server-side program named in the ACTION attribute of the form If the method is GET, the
query string will be appended to the URL prepended with a question mark, visible in the
location box of the browser If the method is POST, the encoded data will be sent as a
Figure 18.15 XML file has been read and processed by Ajax and the DOM.
Trang 6message body in an HTTP header to the server This POST data will not be visible in the
location box and is not limited in size so this method is normally used to send data from
a form The server-side program (e.g., PHP, ASP.NET, CGI), will then process the data
and send back its response in a brand new page while the user waits Example 18.12 is
a traditional HTML form
A Traditional HTML Form
When creating HTML forms with AJAX, the <form> tag will not be given an ACTION
or a METHOD attribute and the submit button will not be used to submit the form data
Instead, an event handler will trigger off the chain of events that deal with the
commu-nication between the browser and server Whether using GET or POST, because Ajax is
making server requests, the user will not have to wait for an entire page to be returned
before continuing to work on the page The next examples will demonstrate how to
cre-ate and process forms with Ajax
The GET Method. Example 18.13 demonstrates how to create an Ajax form using the
GET method The example can be divided into four parts First the program checks for
the type of browser being used and creates the Ajax request object The second part
cre-ates the Ajax functions that will send a request to the server, check for the state of the
server, and when the server completes a request, will handle the data that comes back
In the next part, the HTML form is created with a div container to hold the data that will
come back from the server Finally the server-side PHP program on the server side
receives the form data from the server, handles it, and sends it back to the server The
PHP program might be responsible for validating logins, sending database queries,
read-ing or writread-ing to files, startread-ing sessions, cookies, and so on
E X A M P L E 1 8 1 2
<html>
<head><title>An HTML Form</title></head>
<body>
1 <form ACTION="http://localhost/guestbook.php" METHOD="post"><p>
<p>
Your name:
2 <input type="text" name="username" size="50" /><br />
Your phone:
<input type="text" name="userphone" size=50/><br />
<p>
3 <input type="submit" value="Submit" />
</form>
</body>
</html>
Trang 7The Ajax Program
E X A M P L E 1 8 1 3
<html>
<head><title>Get method Ajax form</title>
<link rel="stylesheet" type="text/css" href="ajaxGETstyle.css" />
<script type="text/javascript" src="ajaxCreateRequest.js">
</script>
<script type="text/javascript">
var ajaxRequest=createRequest();
if(ajaxRequest != false){
2 ajaxRequest.onreadystatechange = function(){
3 var textObj=document.getElementById("message");
if(ajaxRequest.readyState == 4){
//alert(ajaxRequest.status);
if(ajaxRequest.status==200){
} } else if(ajaxRequest.status == 404){
textObj.innerHTML="Resource unavailable";
} else{
textObj.innerHTML="Error!!";
} }
var namevalue=
5 encodeURIComponent(document.getElementById("username").value)
var phonevalue=
encodeURIComponent(document.getElementById("userphone").value)
6 ajaxRequest.open("GET","http://localhost/ajaxform.php?username="+
namevalue+"&userphone="+phonevalue, true);
ajaxRequest.setRequestHeader('If-Modified-Since',
'Sat, 03 Jan 2010 00:00:00GMT');
7 ajaxRequest.send(null);
} else{alert("Browser encountered a problem!");}
} // End goAjax()function
</script>
</head>
<body>
8 <form action="">
Your name: <input type="text" size=50 id=username
name='username' /> <br />
<p>
Your phone: <input type="text" size=50 id=userphone
name="userphone" /><br />
Trang 8<p>
9 <input type="button" value="submit" onClick="goAjax()"; />
</form>
10 <div id="message" class="divStyle">
</div>
</body>
</html>
E X P L A N A T I O N
1 The goAjax() function is returned an XMLHttpRequest object from the
createRe-quest() function found in the external js file called “ajaxCreateRequest.js” shown
in Example 18.14 The CSS style sheet is in Example 18.15
2 The onreadystate event handler will start the callback function when the state of
the server request changes
3 The getElementById() method will return a reference to the div container using its
id called “message”.
4 When the server has completed successfully, its response will be returned as text
The innerHTML property contains the response text that is assigned to the div
container on line 10 and will be displayed in the browser
5 To avoid unexpected requests to the server, the encodeURIComponent encodes any
user-entered parameters that will be passed as part of a URI The value typed by
the user into the form for the username will be assigned to the variable namevalue.
6 The XMLHttpRequest object is initialized It will use the GET method The URL is
a server-side PHP program (Example 18.16) that will be passed parameters,
ap-pended to a ?, consisting of the user’s name and phone number
7 An XMLHttpRequest is sent to the server.
8 The HTML form starts here Notice the ACTION and METHOD attributes are
NOT specified as they are in non-Ajax forms
9 Even though this button looks like a “submit” button, it is really an ordinary
but-ton with an onClick event handler that when clicked, will start the goAjax()
func-tion In non-Ajax form submission, the submit button normally causes the
con-tents of the form to be sent to the URL assigned to the form’s ACTION attribute
10 The div container will display the results that were returned to the server from
the PHP program listed as a parameter in the open() method on line 6.
E X A M P L E 1 8 1 3 (C O N T I N U E D)
Trang 9The File to Create an Ajax Request Object
The CSS Style Sheet File
E X A M P L E 1 8 1 4
/* Check browser type and create ajax request object */
function createRequest(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
} }
}
return ajaxRequest;
}
E X A M P L E 1 8 1 5
body{background-color:blue;color:white;font-size:120%}
.divStyle {
background-color:lightblue;
margin-left:50px;
margin-right:100px;
border-style:solid;
color:darkblue;
font-size:120%
}
Trang 10The Server-Side PHP Script
E X A M P L E 1 8 1 6
<?php
1 extract($_REQUEST);
2 if( empty($username)){
3 echo "<span style='color:red'>Please enter your name
</span><br />";
}
5 if (empty($userphone)){
echo "<span style='color:red'>Please enter your phone number
</span><br />";
exit;
}
6 echo "Welcome <b>$username</b> Your phone number is
<b>$userphone</b>.";
?>
E X P L A N A T I O N
1 This PHP function extracts the data from a global associative array called
$_REQUEST It contains any name/value pairs submitted from the HTML form
and sent with either GET or POST requests; in this example, the array contains
two sets of name/value pairs:
username => “Ebenezer Scrooge”
userphone => “0207 626 4388”
PHP’s extract function creates a variable, $username, for the name and assigns it
the value “Ebenezer Scrooge” and another variable called $userphone with a value
of “0207 626 4388” (This information was sent in the server request in a
param-eter: ?username="namevalue+"&userphone="+phonevalue Figure 18.16 shows a
completed form
2 If the variable is empty (i.e., null), tell the user
3 If the user didn’t enter anything in the textfield, he or she will be sent this message
in red letters defined by the <span> tag (see Figure 18.17).
4 The PHP program exits here
5 If the user doesn’t type anything in the phone field, he will get a message in red
telling him or her to enter his or her phone number (see Figure 18.18)
6 The PHP program echo’s a string of text to the server The server will respond by
sending the text to the Ajax program where it will be received (line 3 in the Ajax
program) and displayed (line 4 in the Ajax program)