📘 Lesson · Lesson 49
AJAX Live Search
AJAX Live Search
About
AJAX live search shows matching results instantly as the user types, without reloading the page.
Search Box + JS
<input type="text" id="search" onkeyup="liveSearch(this.value)">
<div id="results"></div>
<script>
function liveSearch(q) {
fetch("search.php?q=" + q)
.then(r => r.text())
.then(html => document.getElementById("results").innerHTML = html);
}
</script>
search.php
$q = "%" . $_GET["q"] . "%";
$stmt = $pdo->prepare("SELECT name FROM students WHERE name LIKE ?");
$stmt->execute([$q]);
foreach ($stmt as $row) {
echo "<p>" . htmlspecialchars($row["name"]) . "</p>";
}
Summary
- JS fetch() sends the typed text to search.php on each keyup.
- PHP queries with LIKE and returns matching HTML instantly.
परिचय
AJAX live search user के type करते ही matching results turant दिखाता है, page reload किए बिना।
Search Box + JS
<input type="text" id="search" onkeyup="liveSearch(this.value)">
<div id="results"></div>
<script>
function liveSearch(q) {
fetch("search.php?q=" + q)
.then(r => r.text())
.then(html => document.getElementById("results").innerHTML = html);
}
</script>
search.php
$q = "%" . $_GET["q"] . "%";
$stmt = $pdo->prepare("SELECT name FROM students WHERE name LIKE ?");
$stmt->execute([$q]);
foreach ($stmt as $row) {
echo "<p>" . htmlspecialchars($row["name"]) . "</p>";
}
सारांश
- JS fetch() हर keyup पर typed text search.php को भेजता है।
- PHP LIKE से query करके matching HTML turant लौटाता है।