Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

Fundamental Ajax

Now that you’ve learned the possible constituent parts of an Ajax application, this section will put those pieces together to produce a working example of this technology in action. Keep at the forefront of your mind one of the main reasons for using Ajax in the first place: to produce interactive sites that respond to user actions but without the interruption that comes from refreshing an entire page.

To achieve the this goal, an Ajax application includes an extra layer of processing that occurs between the requested web page and the web server responsible for producing that page. This layer is commonly referred to as an Ajax Framework (also an Ajax Engine). The framework exists to handle requests between the user and the web server, and it communicates the requests and responses without additional actions such as redrawing a page and without interruption to whatever actions the user is currently performing, such as scrolling, clicking, or reading a block of text.

In the next few sections, you’ll learn how the different parts of an Ajax application function together to produce a streamlined user experience.

The XMLHTTPRequest Object

Earlier in this chapter, you learned about HTTP requests and responses and also how client-side programming can be used within an Ajax application. The specific JavaScript object called XMLHTTPRequest is crucial when connecting with the web server and making a request without entirely reloading the original page.

The XMLHTTPRequest object is often referred to as the “guts” of any Ajax application given that it is the gateway between the client request and the server response. Although you will soon learn the basics of creating and using an instance of the XMLHTTPRequest object, see http://www.w3.org/TR/XMLHttpRequest/ for a more detailed understanding.

The XMLHTTPRequest object has several attributes, as shown in Table 34.1.

Table 34.1 Attributes of the XMLHTTPRequest Object

Attribute

Description

onreadystatechange

Specifies the function that should be invoked when the readyState property changes.

readyState

The state of the of request, represented by integers 0 (uninitialized), 1 (loading), 2 (loaded), 3 (interactive), and 4 (completed).

responseText

Contains data returned as a string of characters.

responseXml

Contains data returned as an XML-formatted document object.

status

An HTTP status code returned by the server, such as 200.

statusText

An HTTP status phrase returned by the server, such as OK.

The XMLHTTPRequest object has several methods, as shown in Table 34.2.

Table 34.2 Methods of the XMLHTTPRequest Object

Method

Description

abort()

Stops the request.

getAllResponseHeaders()

Returns all the headers in the response as a string.

getResponseHeader(header)

Returns the value of header header as a string.

open('method', 'URL', 'a')

Specifies the HTTP method method (such as POST or GET), the target URL URL, and whether the request should be asynchronous (where a is ‘true’) or not (where a is false).

send(content)

Sends the request, with optional POST content content.

setRequestHeader('x', 'y')

Sets a parameter (x) and value (y) pair and sends it as a header with the request.

Before using the functionality of XMLHTTPRequest, you must first create an instance of it. This necessitates a bit more than simply typing

var request = new XMLHTTPRequest();

Although the preceding snippet of JavaScript would work on non-Internet Explorer browsers, ideally you want your code to work for everyone. Thus, the following JavaScript is a solution for creating a new instance of the XMLHTTPRequest object on all browsers:

function getXMLHTTPRequest() {   var req = false;
  try { 
   /* for Firefox */
   req = new XMLHttpRequest(); 
  } catch (err) { 
   try { 
     /* for some versions of IE */
     req = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (err) { 
     try { 
      /* for some other versions of IE */
      req = new ActiveXObject("Microsoft.XMLHTTP");
     } catch (err) { 
       req = false;
     } 
   } 
  } 
  return req;
} 

If you place this bit of JavaScript in a file called ajax_functions.js and place it on your web server, you have the beginning of an Ajax library of functions.

When you want to create an instance of XMLHTTPRequest in your Ajax application, you include the file that contains your functions:

<script src="ajax_functions.js" type="text/javascript"></script>

And then invoke the new object and carry on with your coding:

<script type="text/javascript">
var myReq = getXMLHTTPRequest();
</script>

In the next section you’ll add the next piece of the puzzle to your Ajax functions file.

Communicating with the Server

With the example in the preceding section, all you have achieved is the creation of a new XMLHTTPRequest object; you haven’t actually performed a communicative task with it. In the following example, you’ll create a JavaScript function that sends a request to the server, specifically to a PHP script called servertime.php.

function getServerTime() { 
 var thePage = 'servertime.php';
 myRand = parseInt(Math.random()*999999999999999);
 var theURL = thePage +"?rand="+myRand;
 myReq.open("GET", theURL, true);
 myReq.onreadystatechange = theHTTPResponse;
 myReq.send(null);
} 

The first line in the function creates a variable called thePage with a value of servertime.php. This is the name of the PHP script that will reside on your server.

The next line may seem out of place, as it creates a random number. The obvious question is “What does a random number have to do with getting the server time?” The answer is that it doesn’t have any direct effect on the script itself. The reason the random number is created, and then appended to the URL in the third line of the function, is to avoid any problems with the browser (or a proxy) caching the request. If the URL were simply http://yourserver/yourscript.php, the results might be cached. However, if the URL is http://yourserver/yourscript.php?rand=randval, there isn’t anything to cache because the URL will be different every time, although the functionality of the underlying script will not change.

The final three lines of the function use three methods (open, onreadystatechange, and send) of the instance of the XMLHTTPRequest object created by calling getXMLHTTPRequest() as seen in the previous section.

In the line using the open method, the parameters are the type of request (GET), the URL (theURL), and a value of true indicating that the request is to be asynchronous.

In the line using the onreadystatechange method, the function will invoke a new function, theHTTPResponse, when the state of the object changes.

In the line using the send method, the function sends NULL content to the server-side script.

At this point, create a file called servertime.php containing the code in Listing 34.1.

Listing 34.1 The Contents of servertime.php

<?php
header('Content-Type: text/xml');
echo "<?xml version=\ "1.0\ " ?>      
   <clock>
    <timestring>It is ".date('H:i:s')." on ".date('M d, Y').".</ timestring>
    </clock>";
?>

This script gets the current server time, through the use of the date() function in PHP, and returns this value within an XML-encoded string. Specifically, the date() function is called twice; once as date('H:i:s'), which returns the hours, minutes, and seconds of the current server time based on the 24-hour clock, and once as date('M d, Y'), which returns the month, date, and year the script was called.

The result string itself will look like the following, with the items in brackets replaced by the actual values:

<?xml version="1.0" ?>
<clock>
  <timestring>
  It is [time] on [date].
  </timestring>
</clock>

In the next section, you’ll create the remaining function, theHTTPResponse(), and do something with the response from the PHP script on the server.

Working with the Server Response

The getServerTime() function in the preceding section is ready to invoke theHTTPResponse() and do something with the string that is returned. The following example interprets the response and gets a string to display to the end user:

function theHTTPResponse() { 
 if (myReq.readyState == 4) { 
  if(myReq.status == 200) { 
    var timeString = 
        myReq.responseXML.getElementsByTagName("timestring")[0];
    document.getElementById('showtime').innerHTML = 
        timeString.childNodes[0].nodeValue;
  } 
 } else { 
  document.getElementById('showtime').innerHTML = 
       '<img src="ajax-loader.gif"/>';
 } 
} 

The outer if...else statement checks the state of the object; if the object is in a state other than 4 (completed), an animation is displayed (<img src="ajax-loader.gif"/>). However, if myReq is in a readystate of 4, the next check is if the status from the server is 200 (OK).

If the status is 200, a new variable is created: timeString. This variable is assigned the value stored in the timestring element of the XML data sent from the server-side script, which is retrieved by using the getElementByTagname method of the response from the object:

var timeString = myReq.responseXML.getElementsByTagName("timestring")[0];

The next step is to display that value in some area defined by CSS in the HTML file. In this case, the value is going to be displayed in the document element defined as showtime:

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

At this point, your ajax_functions.js script is complete; see Listing 34.2.

Listing 34.2 The Contents of ajax_functions.js

function getXMLHTTPRequest() { 
  var req = false;
  try { 
   /* for Firefox */
   req = new XMLHttpRequest(); 
  } catch (err) { 
   try { 
     /* for some versions of IE */
     req = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (err) { 
     try { 
      /* for some other versions of IE */
      req = new ActiveXObject("Microsoft.XMLHTTP");
     } catch (err) { 
      req = false;
     } 
   } 
  } 
  
  return req;
} 

function getServerTime() { 
 var thePage = 'servertime.php';
 myRand = parseInt(Math.random()*999999999999999);
 var theURL = thePage +"?rand="+myRand;
 myReq.open("GET", theURL, true);
 myReq.onreadystatechange = theHTTPResponse;
 myReq.send(null);
} 

function theHTTPResponse() { 
 if (myReq.readyState == 4) { 
  if(myReq.status == 200) { 
    var timeString = 
      myReq.responseXML.getElementsByTagName("timestring")[0];

Listing 34.2 Continued

    document.getElementById('showtime').innerHTML = 
      timeString.childNodes[0].nodeValue;
  } 
 } else { 
  document.getElementById('showtime').innerHTML = 
      '<img src="ajax-loader.gif"/>';
 } 
} 

In the next section, you will finalize the HTML and put all the pieces together to create a single Ajax application.

Putting It All Together

As you learned earlier in this chapter, Ajax is a combination of technologies. In the preceding sections you have used JavaScript and PHP—client-side and server-side programming—to make an HTTP request and retrieve a response. The missing piece of the technological puzzle is the display portion: using XHTML and CSS to produce the result for the user to see.

Listing 34.3 shows the contents of ajaxServerTime.html, the file that contains the style sheet entries and the calls to the JavaScript that invokes the PHP script and then retrieves the response from the server.

Listing 34.3 The Contents of ajaxServerTime.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr" lang="en">
<head>

<style>
body { 
 background: #fff;
 font-family: Verdana, sans-serif;
 font-size: 12pt;
 font-weight: normal;
} 

.displaybox { 
  width: 300px;
  height: 50px;
  background-color:#ffffff;
  border:2px solid #000000;
  line-height: 2.5em;
  margin-top: 25px;
  font-size: 12pt;
  font-weight: bold;
} 
</style>

<script src="ajax_functions.js" type="text/javascript"></script>
<script type="text/javascript">
var myReq = getXMLHTTPRequest();
</script>

</head>

<body>

<div align="center">
  <h1>Ajax Demonstration</h1>
  <p align="center">Place your mouse over the box below 
  to get the current server time.<br/>
  The page will not refresh; only the contents of the box 
  will change.</p>
  <div id="showtime" class="displaybox" 
      onmouseover="javascript:getServerTime();"></div>
</div>

</body>
</html>

The listing begins with the XHTML declaration, followed by the opening <html> and <head> tags. Within the head area of the document, place the style sheet entries within the <style></style> tag pair. Only two are defined here: the format of everything within the body tag, and the format of the element using the displaybox class. The displaybox class is defined as a 300-pixel wide, 50-pixel high white box with a black border. Additionally, everything in it will be in a bold 12-point font.

After the style sheet entries, but still within the head element, is the link to the JavaScript library of functions:

<script src="ajax_functions.js" type="text/javascript"></script>

This is followed by the creation of a new XMLHTTPRequest object called myReq:

<script type="text/javascript">
var myReq = getXMLHTTPRequest();
</script>

The head element is then closed and the body element begins. Within the body element, only XHTML is present. Within a centered div element, you will find the text for the page heading (Ajax Demonstration) as well as the instructions for users to place their mouse over the box below to get the current server time.

It is within the attributes of the div element with the id of showtime that the action really takes place, specifically within the onmouseover event handler:

<div id="showtime" class="displaybox" onmouseover="javascript:getServerTime();"></div>

The use of onmouseover means that when the user’s mouse enters the area defined by the div called showtime, the JavaScript function getServerTime() is invoked. Invoking this function initiates the request to the server, the server responds, and the resulting text appears within this div element.

Figures 34.1, 34.2, and 34.3 show the sequence of events when these scripts are in action. At no time does the ajaxServerTime.html reload; only the contents of the div called showtime.

Figure 34.1

Figure 34.1 Initially loading ajaxServerTime.html shows instructions and a blank box.

Figure 34.2

Figure 34.2 The user mouses over the area and starts the request; the icon indicates that the object is loading.

Figure 34.3

Figure 34.3 The result from the server is displayed in the div called showtime; mousing over the area again results in another invocation of the script.

  • + Share This
  • 🔖 Save To Your Account