PHP Example - AJAX Live Search
AJAX can provide users with a friendlier and more interactive search experience.
AJAX Live Search
In the example below, we will demonstrate a live search that returns results as you type.
Live search has many advantages over traditional search:
- Matching results are displayed as you type
- Results are filtered as you continue to type
- If there are too few results, deleting characters widens the scope
Enter "HTML" in the text box below to search for pages containing HTML:
The results in the example above are looked up in an XML file (links.xml). To keep this example small and simple, we provide only 6 results.
Example Explanation - HTML Page
When the user types characters in the input box above, the "showResult()" function is executed. This function is triggered by the "onkeyup" event:
Source code explanation:
If the input box is empty (str.length==0), the function clears the content of the livesearch placeholder and exits the function.
If the input box is not empty, then showResult() performs the following steps:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send a request to the file on the server
- Note the parameter (q) appended to the end of the URL (containing the input box content)
PHP File
The server page called via JavaScript above is a PHP file named "livesearch.php".
The source code in "livesearch.php" searches the XML file for titles matching the search string and returns the results:
load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
// Get the value of parameter q from the URL
$q=$_GET["q"];
// If the q parameter exists, search for data in the xml file
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 links matching the search
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="" .
$y->item(0)->childNodes->item(0)->nodeValue . "";
}
else
{
$hint=$hint . "
" .
$y->item(0)->childNodes->item(0)->nodeValue . "";
}
}
}
}
}
// If not found, return "no suggestion"
if ($hint=="")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
// Output result
echo $response;
?>
If JavaScript sends any text (i.e., strlen($q) > 0), the following happens:
- Load the XML file into a new XML DOM object
- Iterate over all the
elements in order to find the text matching what JavaScript sent - Set the correct URL and title in the "$response" variable. If more than one match is found, all matches are added to the variable.
- If no match is found, set the $response variable to "no suggestion".