Paperback - 240 pages
Published by Sams
Date Published: April 2006
ISBN: 0672328682 Buy a Copy
I recently received the following email from one of my contacts at Sams
I hope you're well! The book, Sams Teach Yourself AJAX in 10 Minutes, by Phil Ballard,
has just been published by Sams Publishing. This book on AJAX, one of the hottest
technologies in web development today will:
Teach the average web developer to build simple but powerful AJAX applications immediately
Provide an accessible, handy reference for the most common features and functions of AJAX
Immediately begin teaching how to solve realistic user interface problems
Equip the reader with the platform from which to build more complex and advanced AJAX applications
About the Author:
Phil Ballard is a professional web consultant specializing in website and intranet design, search
engine optimization, server-side scripting, client-side design and programming and hosting. Ballard
has written a number of online tutorials, including the most popular of late, on AJAX.
Table of Contents:
I. A Refresher on Web Technologies
1. Anatomy of a Website
2. Writing Web Pages in HTML
3. Sending Requests Using the HTTP Protocol
4. Client-side Coding Using JavaScript
5. Server-side Programming in PHP
6. A Brief Introduction to XML
II. Introducing AJAX
7. Anatomy of an AJAX Application
8. Formatting the XMLHTTP Request
9. Monitoring the Server's Status
10. Using the Returned Data
11. Our First AJAX Application
III. More Complex AJAX Techniques
12. Returning Data as Text
13. Returning Data as a JavaScript Object
14. Returning Data as XML
15. Using the REST Protocol
16. Web Services Using SOAP
17. Building an AJAX Library in JavaScript
18. AJAX 'Gotchas'
Please feel free to reply to this email for review copies, chapter excerpts or an author interview. Thank you!
So naturally I did and here's the sample chapter they sent over for you all to peruse. It uses PHP instead of
ASP, but that's such a small portion of the chapter and the PHP involved is so simple I didn't think that it
would take away from anyone's understanding of the concepts involved. Anyway... if you're looking to get
started with Ajax, give it a read.
LESSON 11 Our First Ajax Application
In this lesson you will learn how to construct a complete and working
Ajax application using the techniques discussed in previous lessons.
Constructing the Ajax Application
The previous lessons have introduced all the techniques involved in the
design and coding of a complete Ajax application. In this lesson, we're
going to construct just such an application.
Our first application will be simple in function, merely returning and displaying the time as read from the server's internal clock; nevertheless it
will involve all the basic steps required for any Ajax application:
An HTML document forming the basis for the application
JavaScript routines to create an instance of the XMLHTTPRequest object and construct and send asynchronous server calls
A server-side routine (in PHP) to configure and return the required information
A callback function to deal with the returned data and use it in the application
Let's get to it, starting with the HTML file that forms the foundation for
our application.
The HTML Document
Listing 11.1 shows the code for our HTML page.
LISTING 11.1 The HTML Page for Our Ajax Application
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Ajax Demonstration</title>
<style>
.displaybox {
width:150px;
background-color:#ffffff;
border:2px solid #000000;
padding:10px;
font:24px normal verdana, helvetica, arial, sans-serif;
}
</style>
</head>
<body style="background-color:#cccccc;text-align:center">
<h1>Ajax Demonstration</h1>
<h2>Getting the server time without page refresh</h2>
<form>
<input type="button" value="Get Server Time" />
</form>
<div id="showtime" class="displaybox"></div>
</body>
</html>
This is a simple HTML layout, having only a title, subtitle, button, and
<div> element, plus some style definitions.
Tip In HTML the <div> ... </div> element stands for
division and can be used to allow a number of page
elements to be grouped together and manipulated in a block.
Figure 11.1 shows what the HTML page looks like.
FIGURE 11.1 The HTML file of Listing 11.1.
Adding JavaScript
We can now add our JavaScript routines to the HTML page. We'll do so
by adding them inside a <script> ... </script> container to the <head>
section of the page.
Tip
Alternatively we could have added the routines in an external JavaScript file
(ajax.js, say) and called this file from our document by using a statement like:
It's now a simple matter to create our XMLHTTPRequest object, which on
this occasion we're going to call http:
var http = getXMLHTTPRequest();
The Server Request
Now we need a function to construct our server request, define a callback
function, and send the request to the server. This is the function that will
be called from an event handler in the HTML page:
function getServerTime() {
var myurl = 'telltimeXML.php';
myRand = parseInt(Math.random()*999999999999999);
// add random number to URL to avoid cache problems
var modurl = myurl+"?rand="+myRand;
http.open("GET", modurl, true);
// set up the callback function
http.onreadystatechange = useHttpResponse;
http.send(null);
}
Once again we have added a parameter with a random value to the URL
to avoid any cache problems. Our callback function is named
useHttpResponse and is called each time a change is detected in the value
of http's readyState property.
Our PHP Server-Side Script
Before explaining the operation of the callback function, we need to refer
to the code of the simple PHP server routine telltimeXML.php, shown in
Listing 11.2.
This short program reports the server time using PHP's date() function.
The argument passed to this function defines how the elements of the date
and time should be formatted. Here we've ignored the date-related elements completely and asked for the time to be returned as
Hours:Minutes:Seconds using the 24-hour clock.
Our server script returns an XML file in the following format:
with XX:XX:XX replaced by the current server time. We will use the callback function to extract this time information
and display it in the <div> container of the HTML page.
The Callback Function
Here is the code for the callback function useHttpResponse:
function useHttpResponse() {
if (http.readyState == 4) {
if(http.status == 200) {
var timeValue = http.responseXML.getElementsByTagName("timenow")[0];
document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;
}
} else {
document.getElementById('showtime').innerHTML = '<img src="anim.gif">';
}
}
Once again we have used the getElementsByTagname method, this time to
select the <timenow> element of the XML data, which we have stored in a
variable timeValue. However, on this occasion we're not going to display
the value in an alert dialog as we did in Lesson 10, "Using the Returned
Data."
This time we want instead to use the information to update the contents of
an element in the HTML page. Note from Listing 11.1 how the <div>
container is defined in our HTML page:
<div id="showtime" class="displaybox"></div>
In addition to the class declaration (which is used in the <style>
definitions to affect how the <div> element is displayed), we see that
there is also defined an id (identity) for the container, with a value set to
showtime.
Currently the <div> contains nothing. We want to update the content of
this container to show the server time information stored in timeValue.
We do so by selecting the page element using JavaScript's
getElementById() method, which we met in Lesson 10. We'll then use
the JavaScript innerHTML property to update the element's contents:
Finally, we must decide how the server requests will be triggered. In this
case we shall slightly edit the HTML document to use the onClick()
event handler of the <button> object:
<input type="button" value="Get Server Time" onClick="getServerTime()">
This will correctly deal with the occasion when the Get Server Time button is clicked. It does, however,
leave the <div> element empty when we
first load the page.
To overcome this little problem, we can use the onLoad() event handler of
the page's <body> element:
function getServerTime() {
var myurl = 'telltimeXML.php';
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http.open("GET", modurl, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
function useHttpResponse() {
if (http.readyState == 4) {
if(http.status == 200) {
var timeValue = http.responseXML.getElementsByTagName("timenow")[0];
document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;
}
} else {
document.getElementById('showtime').innerHTML = '<img src="anim.gif">';
}
}
</script>
</head>
<body style="background-color:#cccccc" onLoad="getServerTime()">
<center>
<h1>Ajax Demonstration</h1>
<h2>Getting the server time without page refresh</h2>
<form>
<input type="button" value="Get Server Time" onClick="getServerTime()">
</form>
<div id="showtime" class="displaybox"></div>
</center>
</body>
</html>
Loading the page into our browser, we can see that the server time is displayed
in the <div> container, indicating that the onLoad event handler for
the <body> of the page has fired when the page has loaded.
User Feedback
Note also that we have provided user feedback via the line
which executes on each change to the value readyState until the condition
readyState == 4
is satisfied. This line loads into the time display element an animated GIF
with a rotating pattern, indicating that a server request is in progress, as
shown in Figure 11.2. This technique was described in more detail in
Lesson 10.
If you have a fast server and a good Internet
connection, it may be difficult to see this user feedback in action because the time display is updated virtually instantaneously. To demonstrate the operation
of the animated GIF image, we can slow down the
server script to simulate the performance of a more
complex script and/or an inferior connection, by using
PHP's sleep() command: