PHP and AJAX Live Search

By | September 28, 2022

AJAX can be used for a more user friendly and interactive search.

AJAX Live Search

In the AJAX example below we will demonstrate a live search, where the server gets search results while the user types.

Live search has many benefits compared to traditional searching:

  • Matching results are shown as you type
  • Results narrow as you continue typing
  • If results become too narrow, remove characters to see a broader result

Search for a W3Schools page in the Box Below

Top of Form

Bottom of Form

This example consists of four pages:

  • a simple HTML form
  • a JavaScript
  • a PHP page
  • an XML document

In this example the results are found in an XML document (links.xml). To make this example small and simple, only eight results are available.

The HTML Form

This is the HTML page. It contains a simple HTML form, style for the form and a link to a 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 Explained – The HTML Form

As you can see, the HTML page above contains a simple HTML form with an input field called “txt1”.

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 showResult() is executed.
  3. Below the form is a <div> called “livesearch”. This is used as a placeholder for the return data of the showResult() function.

The JavaScript

The JavaScript code is stored in “livesearch.js” and linked to 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 Explained

The GetXmlHttpObject function is the same as in the PHP AJAX Suggest chapter.

The showResult() Function

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

If there is no input in the text field (str.length == 0) the function sets the return field to empty and removes any border around it.

However, if there is any input in the text field 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

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 txtHint placeholder is filled with the response text, and a border is set around the return field. 

The PHP Page

The server page called by the JavaScript code is a PHP file called “livesearch.php”.

The code in the “livesearch.php” checks the XML document “links.xml”. This document contains titles and URL’s of some pages on W3Schools.com.

The code searches the XML file for titles matching the search string and returns the result as 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;
?>

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

  1. PHP creates an XML DOM object of the “links.xml” file
  2. All  “title” elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript
  3. The link containing the correct title is found and set as the “$response” variable. If more than one match is found, all matches are added to the variable
  4. If no matches are found the $response variable is set to “no suggestion”
  5. The $result variable is output and sent to the “livesearch” placeholder
Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *