AJAX Example

In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a web form.

Type a Name in the Box Below NOTE CLICK HERE TO SEE WORK---this won't work here because of Cross-Domain origin restriction

First Name:

Suggestions:


PHP CODE

Example Explained - The HTML Form

The form above has the following HTML code:

<form> 
First Name:
<input type="text" id="txt1"  onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

As you can see it is just a simple HTML form with an input field called "txt1".

An event attribute for the input field defines a function to be triggered by the onkeyup event.

The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for data retrieved from the web server.

When the user inputs data, a function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time the user moves his finger away from a keyboard key inside the input field, the function showHint is called.


Example Explained - The showHint() Function

The showHint() function is a very simple JavaScript function placed in the <head> section of the HTML page.

The function contains the following code:

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="http://YOURPATH/getHint.php";  // for example my path is http://puzzle.sci.csueastbay.edu/~grewe/HelloWorldPhp/src/getHint.php
  url=url+"?q="+str;
  url=url+"&sid="+Math.random();
  xmlHttp.onreadystatechange=stateChanged;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

The function executes every time a character is entered in the input field.

If there is some input in the text field (str.length > 0) the function executes the following:

  • Defines the url (filename) to send to the server
  • Adds a parameter (q) to the url with the content of the input field
  • Adds a random number to prevent the server from using a cached file
  • Creates an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
  • Opens the XMLHTTP object with the given url.
  • Sends an HTTP request to the server

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


Example Explained - The stateChanged() Function

The stateChanged() function contains the following code:

function stateChanged() 
{ 
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
     document.getElementById("txtHint").innerHTML=xmlHttp.responseText; 
  } 
} 

The stateChanged() function executes every time the state of the XMLHTTP object changes.

When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled with the response text. 



Example Explained - The GetXmlHttpObject() Function

 

The example above calls a function called GetXmlHttpObject().

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

The function is listed below:

function GetXmlHttpObject()  {
  var xmlHttp=null;
  try
    {    // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();    } 
  catch (e)
    {    // see if following will work
         try
         {
             xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      }
         catch (e)
         {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      }
    }

  return xmlHttp;
}

 


PHP code gethint.php

<?php
$a = array(30);

//'Fill up array with names
$a[0]="Anna"
$a[1]="Brittany"
$a[2]="Cinderella"
$a[3]="Diana"
$a[4]="Eva"
$a[5]="Fiona"
$a[6]="Gunda"
$a[7]="Hege"
$a[8]="Inga"
$a[9]="Johanna"
$a[10]="Kitty"
$a[11]="Linda"
$a[12]="Nina"
$a[13]="Ophelia"
$a[14]="Petunia"
$a[15]="Amanda"
$a[16]="Raquel"
$a[17]="Cindy"
$a[18]="Doris"
$a[19]="Eve"
$a[20]="Evita"
$a[21]="Sunniva"
$a[22]="Tove"
$a[23]="Unni"
$a[24]="Violet"
$a[25]="Liza"
$a[26]="Elizabeth"
$a[27]="Ellen"
$a[28]"Wenche"
$a[29]="Vicky"

//'get the q parameter from URL
$q=$_GET["q"];

//'lookup all hints from array if length of q>0
if strlen($q)>0 then
{ hint="";
foreach ($a as $element)
if($q in start of $element)
if hint=""
hint=$element;
else
hint=hint + " , " + $element;
}

//'Output "no suggestion" if no hint were found
return $hint;
?>

 

 

 

 

 

© Lynne Grewe