PHP and AJAX Live Search

AJAX can provide users with a more friendly and interactive search experience.

AJAX Live Search

In the following AJAX example, we will demonstrate a real-time search.

Real-time search has many advantages over traditional search:

  • Matching results are displayed as data is entered
  • Results are filtered as data is continued to be entered
  • If there are too few results, deleting characters can provide a wider range

Search for pages on CodeW3C.com in the text box below

This example includes four elements:

  • Simple HTML Form
  • JavaScript
  • PHP page
  • XML Document

In this example, the results are in an XML document (links.xmlin the ) for the search. To keep this example small and simple, we only provide 8 results.

HTML Form

This is an HTML page. It includes a simple HTML form, CSS styles for the form, and a link to the JavaScript:

<html>
<head>
<script src="livesearch.js"></script> 
<style type="text/css"> 
#livesearch
  { 
  margin:0px;
  width:194px; 
  }
#txt1
  { 
  margin:0px;
  } 
</style>
</head>
<body>
<form>
<input type="text" id="txt1" size="30"
onkeyup="showResult(this.value)"
<div id="livesearch"></div>
</form>
</body>
</html>

Example Explanation - HTML Form

As you can see, the HTML page contains a simple HTML form with a text box named "txt1".

How the form works:

  1. An event is triggered when the user presses and releases a key in the text box
  2. When an event is triggered, the function named showResult() is executed
  3. Below the form is a <div> element named "livesearch". It serves as a placeholder for the data returned by showResult()

JavaScript

JavaScript code is stored in the "livesearch.js" file associated with the HTML document:

var xmlHttp
function showResult(str)
{
if (str.length==0)
 { 
 document.getElementById("livesearch").
 innerHTML="";
 document.getElementById("livesearch").
 style.border="0px";
 return
 }
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="livesearch.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("livesearch").
 innerHTML=xmlHttp.responseText;
 document.getElementById("livesearch").
 style.border="1px solid #A5ACB2";
 } 
}
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:

GetXmlHttpObject with PHP and AJAX Requests has the same example.

The showResult() function

This function is executed each time a character is input into the text box.

If there is no input in the text area (str.length == 0), the function sets the return field to empty and removes any surrounding borders.

However, if there is input in the text area, the function executes:

  1. Define the url (file name) to be sent to the server
  2. Add the parameter (q) with the content of the input box to the url
  3. Add a random number to prevent the server from using a cached file
  4. The GetXmlHttpObject function is used to create an XMLHTTP object, and it informs the function to execute one named stateChanged when a change is triggered
  5. Use the given url to open the XMLHTTP object
  6. Send an HTTP request to the server

stateChanged() function

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

When the state becomes 4 (or "complete"), the response text is used to fill the content of the txtHint placeholder, and a border is set around the returned field.

PHP page

The server page called by JavaScript code is a PHP file named "livesearch.php".

The code in "livesearch.php" checks the XML document "links.xml". This document contains the titles and URLs of some pages on codew3c.com.

This code will search for titles in the XML file that match the search string and return the results in HTML:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
 {
 $y=$x->item($i)->getElementsByTagName('title');
 $z=$x->item($i)->getElementsByTagName('url');
 if ($y->item(0)->nodeType==1)
  {
  //find a link matching the search text
  if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
   {
   if ($hint=="")
    {
    $hint="<a href='" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "' target='_blank'>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   else
    {
    $hint=$hint . "<br /><a href='" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "' target='_blank'>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   }
  }
 }
}
//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;
?>

Example Explanation:

If any text is sent from JavaScript (strlen($q) > 0), the following will occur:

  1. A PHP XML DOM object for creating the "links.xml" file
  2. Traverse all "title" elements (nodetypes = 1) to find the match for the name passed by JavaScript
  3. Find the link containing the correct title and set it to the "$response" variable. If more than one match is found, all matches will be added to the variable
  4. If no match is found, set the $response variable to "no suggestion"
  5. $result is the output sent to the "livesearch" placeholder