AJAX Live Search

PHP AJAX Live Search

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!


How It Works

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).

1. The Frontend

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>

2. The Backend PHP (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-&gt;item(0)-&gt;nodeType == 1) {
  // Find a link matching the search text
  if (stristr($y-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue, $q)) {
    
    // Format the output as an HTML hyperlink
    if ($hint == "") {
      $hint = "&lt;a href='" . 
      $z-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue . 
      "' target='_blank'&gt;" . 
      $y-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue . "&lt;/a&gt;";
    } else {
      $hint .= "&lt;br /&gt;&lt;a href='" . 
      $z-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue . 
      "' target='_blank'&gt;" . 
      $y-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue . "&lt;/a&gt;";
    }
  }
}

} }

// If no hint was found, suggest "no suggestion" if ($hint == "") { $response = "no suggestion"; } else { $response = $hint; }

// Send the response to the frontend echo $response; ?>

What Makes This Powerful?

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!


Exercise

?

Which HTML event is most commonly used to trigger an AJAX Live Search?