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.
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.
// 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();
}
// 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();
?>
As the user types, matching names or emails appear instantly below the input field. The page never reloads, providing a smooth and responsive experience.
This example demonstrates real-time interaction between frontend and backend using AJAX calls triggered by user input.