ASP 101 - Active Server Pages 101 - Web06
The Place ASP Developers Go!



Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates
ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash



 Top ASP 101 Stories Top ASP 101 Stories
Migrating to ASP.NET
Getting Scripts to Run on a Schedule
The Top 10 ASP Links @ Microsoft.com

QUICK TIP:
Don't touch that mouse!
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates


Teach Yourself Ajax in 10 Minutes

from Sams

Teach Yourself Ajax in 10 Minutes
by Phil Ballard

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
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:

<script language="JavaScript" type="text/javascript" src="ajax.js"></script>

in the <head> section of the document.

The XMLHTTPRequest Object

First, let's add our function to create our XMLHTTPRequest object:

function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
    try {
    req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (err2) {
        try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (err3) {
            req = false;
        }
    }
}
return req;
}

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.

LISTING 11.2 telltimeXML.php


<?php
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" ?><clock1><timenow>".date('H:i:s')."</timenow></clock1>";
?>

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:

<?xml version="1.0" ?>
<clock1>
    <timenow>
    XX:XX:XX
    </timenow>
</clock1>

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:

document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;

Employing Event Handlers

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:

<body style="background-color:#cccccc" onLoad="getServerTime()">

This event handler fires as soon as the <body> area of the page has finished loading.

Putting It All Together

Listing 11.3 shows the complete client-side code for our Ajax application.

LISTING 11.3 The Complete Ajax Application


<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>
<script language="JavaScript" type="text/javascript">
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
    try {
    req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (err2) {
        try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (err3) {
            req = false;
        }
    }
}
return req;
}

var http = getXMLHTTPRequest();

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

document.getElementById('showtime').innerHTML = '<img src="anim.gif">';

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:

<?php
header('Content-Type: text/xml');
sleep(3);
echo "<?xml version=\"1.0\" ?><clock1><timenow>".date('H:i:s')."</timenow></clock1>";
?>

The line

sleep(x);

Forces the server to pause program execution for x seconds.

FIGURE 11.2
FIGURE 11.2 An animated image provides user feedback.

Now, each time we click on the Get Server Time button, the time display is updated. Figure 11.3 shows the completed application.

FIGURE 11.3
FIGURE 11.3 Our completed Ajax application.

Summary

In this lesson, we constructed a simple yet complete Ajax application that does the following:

  • Creates an instance of the XMLHTTPRequest object

  • Reacts to JavaScript event handlers built into an HTML page

  • Constructs and sends asynchronous server requests

  • Parses XML received from the server using JavaScript DOM methods

  • Provides user feedback that a request is in progress

  • Updates the displayed page with the received data

This completes Part II of the book. Part III, "More Complex Ajax Technologies," investigates some more advanced Ajax techniques.


Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers