AJAX Live Search
Creating real-time search functionality with AJAX and PHP
🔍 What is AJAX Live Search?
AJAX Live Search displays search results instantly as users type without page refresh. It sends requests to the server asynchronously and updates results dynamically for better user experience.
// Simple AJAX request
function search(query) {
fetch('search.php?q=' + query)
.then(response => response.text())
.then(data => document.getElementById('results').innerHTML = data);
}
Demo:
Live Search Components
HTML Form
Input field for user queries
<input type="text"
onkeyup="search(this.value)"
placeholder="Search...">
JavaScript
Handles AJAX requests
function search(query) {
fetch('search.php?q=' + query)
.then(r => r.text())
}
PHP Backend
Processes search queries
<?php
$q = $_GET['q'];
// Search database
echo $results;
?>
Results Display
Shows search results dynamically
<div id="results">
<!-- Results here -->
</div>
🔹 HTML Search Form
Create an input field that triggers the search function on every keystroke. The onkeyup event calls JavaScript to send AJAX requests as users type.
<!DOCTYPE html>
<html>
<head>
<title>Live Search</title>
<script src="search.js"></script>
</head>
<body>
<h2>Search Names</h2>
<input type="text"
id="searchBox"
onkeyup="liveSearch(this.value)"
placeholder="Type a name...">
<div id="searchResults">
<p>Start typing to search...</p>
</div>
</body>
</html>
Output:
Search Names
Start typing to search...
🔹 JavaScript AJAX Function
The JavaScript function sends search queries to the server using the Fetch API. It updates the results div with the server response without refreshing the page.
// search.js
function liveSearch(query) {
// Don't search if input is empty
if(query.length == 0) {
document.getElementById('searchResults').innerHTML =
'<p>Start typing to search...</p>';
return;
}
// Show loading message
document.getElementById('searchResults').innerHTML =
'<p>Searching...</p>';
// Send AJAX request
fetch('search.php?q=' + encodeURIComponent(query))
.then(response => response.text())
.then(data => {
document.getElementById('searchResults').innerHTML = data;
})
.catch(error => {
document.getElementById('searchResults').innerHTML =
'<p>Error loading results</p>';
});
}
How it works:
1. User types in search box
2. JavaScript sends query to PHP
3. PHP searches database
4. Results display instantly
🔹 PHP Search Backend
The PHP script receives the search query, searches through data, and returns matching results. This example searches an array of names and returns HTML formatted results.
<?php
// search.php
$query = $_GET['q'];
// Sample data (in real app, query database)
$names = array(
"John Smith",
"Jane Doe",
"Bob Johnson",
"Alice Williams",
"Charlie Brown",
"Diana Prince"
);
// Search for matches
$results = array();
foreach($names as $name) {
if(stripos($name, $query) !== false) {
$results[] = $name;
}
}
// Display results
if(count($results) > 0) {
echo "<ul style='list-style: none; padding: 0;'>";
foreach($results as $result) {
echo "<li style='padding: 8px; border-bottom: 1px solid #eee;'>$result</li>";
}
echo "</ul>";
} else {
echo "<p>No results found for '$query'</p>";
}
?>
Sample Output (searching "jo"):
- John Smith
- Bob Johnson
🔹 Database Search Example
For real applications, search a database instead of arrays. This example shows how to safely query a MySQL database using prepared statements to prevent SQL injection.
<?php
// search_db.php
$query = $_GET['q'];
// Database connection
$conn = mysqli_connect("localhost", "username", "password", "database");
// Prepare statement to prevent SQL injection
$stmt = $conn->prepare("SELECT name, email FROM users WHERE name LIKE ? LIMIT 10");
$searchTerm = "%$query%";
$stmt->bind_param("s", $searchTerm);
$stmt->execute();
$result = $stmt->get_result();
// Display results
if($result->num_rows > 0) {
echo "<ul style='list-style: none; padding: 0;'>";
while($row = $result->fetch_assoc()) {
echo "<li style='padding: 10px; border-bottom: 1px solid #eee;'>";
echo "<strong>" . htmlspecialchars($row['name']) . "</strong><br>";
echo "<small>" . htmlspecialchars($row['email']) . "</small>";
echo "</li>";
}
echo "</ul>";
} else {
echo "<p>No results found</p>";
}
$stmt->close();
$conn->close();
?>
Sample Output:
-
John Smith
[email protected] -
Jane Doe
[email protected]
🔹 Enhanced Search with Highlighting
Improve user experience by highlighting the search term in results. This makes it easier for users to see why each result matched their query.
<?php
// search_highlight.php
$query = $_GET['q'];
$names = array("John Smith", "Jane Doe", "Bob Johnson");
$results = array();
foreach($names as $name) {
if(stripos($name, $query) !== false) {
// Highlight matching text
$highlighted = preg_replace(
"/($query)/i",
'<mark style="background: yellow;">$1</mark>',
$name
);
$results[] = $highlighted;
}
}
if(count($results) > 0) {
echo "<ul style='list-style: none; padding: 0;'>";
foreach($results as $result) {
echo "<li style='padding: 8px; border-bottom: 1px solid #eee;'>$result</li>";
}
echo "</ul>";
} else {
echo "<p>No results found</p>";
}
?>
Output (searching "jo"):
- Jo hn Smith
- Bob Jo hnson