TechTip: PHP and AJAX, a Great Pairing

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Using AJAX reduces server-side processor utilization.

 

All of us (including me) run into the issue of not having time to sit down and learn about new technologies and new tools. Recently, I attended a session given by Craig Pelkie on AJAX and CGIDEV2. It was a great session, and I learned a lot (thanks, Craig!). But it also got me thinking about how easy it would be to use PHP with AJAX as well. I decided that my next PHP project was going to incorporate AJAX. The results are detailed here.

What Is AJAX?

I suppose I should start by explaining what AJAX is. AJAX is an acronym for Asynchronous JavaScript and XML...which tells you almost nothing (perhaps I should have been a politician?). The simplest way to explain AJAX is to show you what it does. Have you ever noticed that when you start to type into a search window (the search field on www.amazon.com, for example) a drop-down starts displaying a list of suggested or similar searches? If not, give it a try now. That sort of response and HTML rendering is made possible by AJAX.

How Does It Work?

AJAX uses a combination of JavaScript, XML, and a tool available in all Web browsers called the XMLHttpRequest. The good news is you don't need to know much about the inner workings of the XMLHttpRequest API in order to use AJAX. The basic JavaScript code that utilizes the XMLHttpRequest API is largely the same for all AJAX applications. I have included a template of this code below:

 

//=======================================================

// JavaScript code. Source member name: selectPlan.js

//=======================================================

var xmlhttp;

 

// Create an instance of the XMLHttpObject

// NOTE: In all browsers except IE, this is implemented using

//       the XMLHttpObject. In IE, it is implemented using an

//       ActiveXObject.

function GetXmlHttpObject()

{

if (window.XMLHttpRequest)

  {

  // code for IE7+, Firefox, Chrome, Opera, Safari

  return new XMLHttpRequest();

  }

if (window.ActiveXObject)

  {

  // code for IE6, IE5

  return new ActiveXObject("Microsoft.XMLHTTP");

  }

return null;

}

 

 

// Send the request to the server

function sendRequest(str)

{

xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)

  {

  alert ("Browser does not support HTTP Request");

  return;

  }

 

// set up the url for the server request

var url="getrateplan.php";

url=url+"?q="+str;

 

// random number to avoid caching

url=url+"&sid="+Math.random();

 

xmlhttp.onreadystatechange=stateChanged;

xmlhttp.open("GET",url,true);

xmlhttp.send(null);

 

}

 

// render or re-render the HTML

function stateChanged()

{

      if (xmlhttp.readyState==4)

      {

            document.getElementById("responseHTML").innerHTML=xmlhttp.responseText;

      }

}

 

As you can see, the JavaScript code contains three functions. The first creates the XMLHttpObject and is a separate function only because we have to create the object differently for Internet Explorer versions prior to IE 7.0. You can use this function in your own AJAX code and probably never change it.

 

The second function is where the request to the server is created and executed. If you are familiar with HTML, you have probably already noticed that we are building a URL. In this case, the URL is a PHP script called "getrateplan.php." In the three lines below, we build the URL and include two parameters passed to the PHP script. The first parameter, called "plan," is the actual rate plan that will be retrieved and subsequently displayed. The second parameter, called "sid," is a random number that is included to defeat the browser's caching; it will not be accessed inside the PHP script.

 

// setup the url for the server request

var url="getrateplan.php";

url=url+"?plan="+str;

 

// random number to avoid caching

url=url+"&sid="+Math.random();

 

Once the URL has been built, we need to do two more things: 1) set the action to take when the response is returned from the server and 2) send the URL request to the server. The action to take when the response from the server is received is completed using the onreadystatechange attribute of the XMLHttpObject. The value of this attribute will change several times as the server request is processed. The last thing we do is send the actual request. To do this, we use the "open" method, which opens the request, and then the "send" method, which actually completes and sends the request.

 

Honestly, these first two functions will change very little from application to application when you are developing. The third function is where you will be making your changes. In the example, I have left this section very simple so that the results can easily be seen and understood in both JavaScript and the associated PHP code. As you gain skill with JavaScript, this code and the associated PHP and HTML will probably gain complexity.

 

As mentioned, the onreadystatechange attribute of the XMLHttpObject will change several times as the request is processed by the server. The only readystate we are really interested in is four (4), which indicates that the request has completed. When the readystate changes to four, we are going to retrieve the HTML response text from the XMLHttpObject and place it in the HTML element called responseHTML. This section may be a bit cryptic if you are unfamiliar with JavaScript objects. You can find a plethora of information about the "document" object at W3Schools.com.

 

document.getElementById("responseHTML").innerHTML=xmlhttp.responseText;

 

This operation is not very clear until we see the HTML associated with it:

 

<!--  Note: HTML source file name: displayrate.phtml  -->  

<html>

<head>

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

</head>

<body>

 

<form>

Select a Rate plan:

<select name="rateplans" onchange="sendRequest(this.value)">

<option value="Plan A">Plan A</option>

<option value="Plan B">Plan B</option>

<option value="Plan C">Plan C</option>

<option value="Plan D">Plan D</option>

</select>

</form>

 

<div id="responseHTML"></div>

 

</body>

</html>

 

Now that we see the HTML, some of the missing pieces start to fall into place. For instance, we see how the JavaScript code is included in the HTML:

 

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

 

We also see how the AJAX function is launched:

 

<select name="rateplans" onchange="sendRequest(this.value)">

 

The line of code above simply calls the sendRequest function and passes the currently selected rate plan from the <option> list; it does this each time the user selects a different rate plan.

 

Finally, we see where our response HTML is embedded into the existing HTML when it is returned:

 

<div id="responseHTML"></div>

 

The responseHTML ID tag in the HTML corresponds to the getElementById('responseHTML') in the JavaScript. Basically, any HTML that is output from the getrateplan.php will be placed into the HTML where the responseHTML element ID is defined.

 

The last part of the puzzle is the PHP script that will return the HTML response. In this case, I have just created a "switch" structure to respond with different output, depending on the rate plan passed to the script. In the real world, you would probably want to be using a database lookup to retrieve the data related to the selected rate plan.

 

<?php

 

$plan = $_GET['plan'];

 

switch ($plan) {

       case "PLAN A":

              echo "Description: Arizona Domestic calls plan" + "<br />";

              echo "Recurring Charge: $9.95" + "<br />";

              echo "Welcome Letter: Yes" + "<br />";

              break;

             

       case "PLAN B":

              echo "Description: California Domestic calls plan" + "<br />";

              echo "Recurring Charge: $12.95" + "<br />";

              echo "Welcome Letter: No" + "<br />";

              break;

             

       case "PLAN C":

              echo "Description: New Mexico International calls plan" + "<br />";

              echo "Recurring Charge: $7.95" + "<br />";

              echo "Welcome Letter: Yes" + "<br />";

              break;

             

       case "PLAN D":

              echo "Description: Nevada International calls plan" + "<br />";

              echo "Recurring Charge: $8.95" + "<br />";

              echo "Welcome Letter: Yes" + "<br />";

              break;

}

?>

 

The switch/case structure works in a similar manner to the select/case in RPG. So the correct information for the specified rate plan will be output, depending on which rate plan was passed in on the URL.

 

Once you have all your code in place, you can test your page by entering the following URL in your Web browser:

 

http://yourwebserver/displayrate.phtml

 

This is a very simple example of what can be done using AJAX. Experiment with it and try out your own applications. If you run into trouble, don't despair! You are not the first, and there are vast amounts of freely available information about AJAX and JavaScript on the Internet.

 

Enjoy!

 

 

Jeff Olen

Jeff Olen is a super-spy now but keeps his cover identity intact by working for video game studios on the East Coast. So when he’s not out killing members of ISIS or rescuing refugees, you can find him playing Wolfenstein II or testing the new Fallout 76 releases at his beach house in Costa Rica. In any case, he can’t be reached. You can email his cat at This email address is being protected from spambots. You need JavaScript enabled to view it.. She will pass on your message…if she feels like it.


MC Press books written by Jeff Olen available now on the MC Press Bookstore.

The IBM i Programmer’s Guide to PHP The IBM i Programmer’s Guide to PHP
Get the scoop on how PHP can—and should—be deployed on IBM systems.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  •  

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: