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 |
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 getElementByTagname 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.