Home > Articles > Programming > PHP

  • 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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020