← Back to Chapters

PHP AJAX Live Search

? PHP AJAX Live Search

? Quick Overview

This topic explains how to build a live search feature using PHP and AJAX. As the user types in the input field, matching records are fetched from a database and displayed instantly without reloading the page.

? Key Concepts

  • AJAX for asynchronous communication
  • PHP for server-side processing
  • MySQL for searching stored records
  • DOM manipulation for live updates

? Syntax & Theory

AJAX sends requests to a PHP script whenever the user types. The PHP script queries the database and returns matching results, which are injected into the page dynamically.

? Code Examples

? View Code Example (HTML + JavaScript)
// Input field that triggers live search on key press
<input type="text" id="search" placeholder="Search users..." onkeyup="liveSearch()">
<div id="results"></div>

// AJAX function to fetch matching results from server
function liveSearch() {
var query = document.getElementById("search").value;
var xhr = new XMLHttpRequest();
xhr.open("GET","search.php?q="+query,true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("results").innerHTML = xhr.responseText;
}
};
xhr.send();
}
? View Code Example (PHP – search.php)
// Database connection configuration
<?php
$conn = new mysqli("localhost","username","password","database");

// Stop execution if connection fails
if ($conn->connect_error) {
die("Connection failed");
}

// Process search query safely
if (isset($_GET["q"])) {
$q = mysqli_real_escape_string($conn,$_GET["q"]);
$sql = "SELECT * FROM users WHERE name LIKE '%$q%' OR email LIKE '%$q%'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<ul>";
while ($row = $result->fetch_assoc()) {
echo "<li>".$row["name"]." (".$row["email"].")</li>";
}
echo "</ul>";
} else {
echo "No results found";
}
}
$conn->close();
?>

? Live Output / Explanation

As the user types, matching names or emails appear instantly below the input field. The page never reloads, providing a smooth and responsive experience.

? Interactive Concept

This example demonstrates real-time interaction between frontend and backend using AJAX calls triggered by user input.

? Use Cases

  • User search in admin dashboards
  • Product filtering in e-commerce sites
  • Contact search systems

✅ Tips & Best Practices

  • Add debounce logic to reduce server load
  • Use prepared statements for better security
  • Return JSON for complex UI rendering

? Try It Yourself

  • Add search for phone or city fields
  • Highlight matched keywords
  • Convert results to JSON and render dynamically