21
Sat, Dec
3 New Articles

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!

 

 

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

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

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • 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

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

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