A "Live Search" is an incredibly popular feature found on modern websites (like Google, Amazon, or Wikipedia). As the user types characters into a search bar, suggestions appear immediately below the input field.
This creates an engaging and highly responsive user experience!
A Live Search works precisely like the hints example we created earlier, but instead of just matching names in a basic array, it usually searches through large external data sources (like an XML file or a MySQL Database).
We use an HTML input field with an onkeyup event. Every single time a user presses and releases a key, the showResult() JavaScript function fires.
<form> <input type="text" size="30" onkeyup="showResult(this.value)" placeholder="Search for links..."> <div id="livesearch"></div> </form>
livesearch.php)When a letter is typed, the request is dispatched to livesearch.php. For this example, let's assume PHP searches an XML file called links.xml to find matching websites.
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");
$x = $xmlDoc->getElementsByTagName('link');
// Get the parameter from the URL
$q = $_GET["q"];
// Set the response hint to blank initially
$hint = "";
// Lookup all links from the XML file if length of q is > 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)) {
// Format the output as an HTML hyperlink
if ($hint == "") {
$hint = "<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
} else {
$hint .= "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}
// If no hint was found, suggest "no suggestion"
if ($hint == "") {
$response = "no suggestion";
} else {
$response = $hint;
}
// Send the response to the frontend
echo $response;
?>
The magic here is that PHP is doing the heavy lifting (parsing an entire XML file or running complex SQL queries) in just a few milliseconds, and pushing the result directly to the screen while the user is still typing their query.
This prevents the user from ever hitting a frustrating "No Results Found" page!
Which HTML event is most commonly used to trigger an AJAX Live Search?