PHP and AJAX Requests

AJAX Request

In the following AJAX example, we will demonstrate how a web page communicates with an online web server when the user enters data into a web form.

Enter your name in the text box below:

Suggestions:

This example includes three pages:

  • A simple HTML form
  • A section of JavaScript
  • A PHP page

HTML Form

This is an HTML form. It includes a simple HTML form and a link to JavaScript:

<html>
<head>
<script src="clienthint.js"></script> 
</head>
<body>
<form> 
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

Example Explanation - HTML Form

As you can see, the HTML page contains a simple HTML form with an input field named "txt1".

How the form works:

  1. An event is triggered when the user presses and releases a key in the input field
  2. When this event is triggered, the function named showHint() is executed
  3. Below the form is a <span> named "txtHint". It serves as a placeholder for the data returned by the showHint() function.

JavaScript

JavaScript code is stored in the "clienthint.js" file, which is linked to the HTML document:

var xmlHttp
function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML=""
  return
  }
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request")
  return
  } 
var url="gethint.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
} 
function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
 } 
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example explanation:

showHint() function

The function is executed once each time a character is entered in the input field.

If there is content in the text box (str.length > 0), the function executes as follows:

  1. Define the URL (file name) to be sent to the server
  2. Add the parameter (q) containing the content of the input field to this URL
  3. Add a random number to prevent the server from using a cached file
  4. Call the GetXmlHttpObject function to create an XMLHTTP object and inform the object to execute the function named stateChanged when the event is triggered
  5. Open this XMLHTTP object using the given URL
  6. Send an HTTP request to the server

If the input field is empty, the function simply clears the content of the txtHint placeholder.

stateChanged() function

The function is executed whenever the state of the XMLHTTP object changes.

Fill the txtHint placeholder with the response text when the state becomes 4 (or "complete").

GetXmlHttpObject() function

AJAX applications can only run in web browsers that fully support XML.

The above code calls the function named GetXmlHttpObject().

The function is used to solve the problem of creating different XMLHTTP objects for different browsers.

This has been explained in the previous section.

PHP page

The server page called by the JavaScript code is a simple server page named "gethint.php".

"gethint.php" of the code will check the name array and then return the corresponding name to the client:

<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
  {
  if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
    if ($hint=="")
      {
      $hint=$a[$i];
      }
    else
      {
      $hint=$hint." , ".$a[$i];
      }
    }
  }
}
//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>

If there is text sent from JavaScript (strlen($q) > 0), then:

  1. Find names that match the characters transmitted by JavaScript
  2. If multiple names are found, include all names in the response string
  3. If no matching names are found, set the response to "no suggestion"
  4. If one or more names are found, set the response to these names
  5. Send the response to the "txtHint" placeholder