Change Language


Follow Navioo On Twitter

AJAX AutoSuggest


AJAX AutoSuggest

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

First Name:

AutoSuggestions:

This example consists of three pages:

  • a simple HTML form
  • a JavaScript
  • a PHP page

The HTML Form

This is the HTML page. It contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="examples/ex2/getdatauser.js"></script> 
</head>
<body>
<form> 
First Name:
<input type="text" id="txtDoc"
onkeyup="GetResult(this.value)">
</form>
<p>AutoSuggestions: <div id="GetResult"></div></p> 
</body>
</html>

Example Explained - The HTML Form

As you can see, the HTML page above contains a simple HTML form with an input field called "txtDoc".

The form works like this:

  1. An event is triggered when the user presses, and releases a key in the input field
  2. When the event is triggered, a function called GetResult() is executed.
  3. Below the form is a <span> called "ViewResult". This is used as a placeholder for the return data of the GetResult() function.

The JavaScript

The JavaScript code is stored in "autocomplete.js" and linked to the HTML document:

var xmlHttp

function GetResult(str)
{
if (str.length==0)
  { 
  document.getElementById("ViewResult").innerHTML=""
  return
  }
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request")
  return
  } 
var url="examples/ex2/AutoSuggest.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("ViewResult").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 Explained

The GetResult() Function

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

  1. Defines the url (filename) to send to the server
  2. Adds a parameter (q) to the url with the content of the input field
  3. Adds a random number to prevent the server from using a cached file
  4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
  5. Opens the XMLHTTP object with the given url.
  6. Sends an HTTP request to the server

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

The stateChanged() Function

This function executes every time the state of the XMLHTTP object changes.

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

The GetXmlHttpObject() Function

AJAX applications can only run in web browsers with complete XML support.

The code above called a function called GetXmlHttpObject().

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

This is explained in the previous chapter.


The PHP Page

The server page called by the JavaScript code is a simple PHP file called "AutoSuggest.php".

The code in the "AutoSuggest.php" checks an array of names and returns the corresponding names to the client:

<?php
// Fill up array with names
$a[0]="Mike";
$a[1]="John";
$a[2]="Antonio";
$a[3]="Liza";
$a[4]="Elizabeth";
$a[5]="Fiona";
$a[6]="Gunda";
$a[7]="Ivan";
$a[8]="Luis";
$a[9]="Johanna";
$a[10]="Kitty";
$a[11]="Linda";
$a[12]="Nina";
$a[13]="Auphelia";
$a[14]="Petunia";
$a[15]="Amanda";
$a[16]="Raquel";
$a[17]="Cindy";
$a[18]="Doris";
$a[19]="Eve";
$a[20]="Evita";
$a[21]="Arthur";
$a[22]="Toni";
$a[23]="Anna";
$a[24]="Violet";
$a[25]="Louis";
$a[26]="Eva";
$a[27]="Ellen";
$a[28]="Marco";
$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)
{
$ret="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($ret=="")
{
$ret=$a[$i];
}
else
{
$ret=$ret." , ".$a[$i];
}
}
}
}

//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($ret == "")
{
$response="no suggestion";
}
else
{
$response=$ret;
}

//output the response
echo $response;
?>

 

If there is any text sent from the JavaScript (strlen($q) > 0) the following happens:

  1. Find a name matching the characters sent from the JavaScript
  2. If more than one name is found, include all names in the response string
  3. If no matching names were found, set response to "no AutoSuggestion"
  4. If one or more matching names were found, set response to these names
  5. The response is sent to the "ViewResult" placeholder

Download here

Ajax Javascript feed

↑ Grab this Headline Animator