← Back to PHP Course | Chapter 15: Web Development | Lesson 12 of 12

PHP AJAX Live Search

एक live search box बिना page reload या search button click किए user के type करते ही अपने results update करता है -- सबसे common और तुरंत satisfying AJAX patterns में से एक। यह एक JavaScript keystroke listener, प्रति keystroke एक AJAX request (आमतौर पर debounced), और database में matches query करने वाला एक PHP endpoint combine करता है।
Syntax
php
$query = $_GET["q"] ?? "";
$matches = array_filter($items, fn($item) => stripos($item, $query) !== false);

header("Content-Type: application/json");
echo json_encode(array_values($matches));

Basic Live Search Structure

एक live search interface में तीन pieces साथ काम करते हैं: एक <input> field जिसमें user type करता है, एक JavaScript listener जो text बदलते ही एक AJAX request fire करता है, और एक PHP endpoint जो database search करके display करने के लिए matches return करता है।

उदाहरण: The Basic Live Search Structure

php
<?php
// Set `$_GET['q']` to "ph"
$_GET['q'] = "ph";
// Declare `$products` as an array: `["php", "python", "java"]`
$products = ["php", "python", "java"];
// Declare `$matches`, set to `array_filter($products, function ($p) { return strpos($p, $_GET['q']) !== false; })`
$matches = array_filter($products, function ($p) { return strpos($p, $_GET['q']) !== false; });
// Print `json_encode(array_values($matches))` to the output
echo json_encode(array_values($matches));
?>

Input सुनना और एक Search Trigger करना

JavaScript का input event हर बार text field की value बदलने पर fire होता है, single keystrokes और pastes सहित -- live search box में सुनने के लिए natural event, क्योंकि यह search text बदलने के हर तरीके को capture करता है।

उदाहरण: Listening for Input and Triggering a Search

php
<?php
// JS: input.addEventListener('input', () => fetch('search.php?q=' + input.value))
$_GET['q'] = "p";
echo json_encode(["query_received" => $_GET['q']]);
?>

Search Requests को Debounce करना

Debouncing search request भेजने में तब तक देरी करता है जब तक user एक छोटे moment (जैसे 300 milliseconds) के लिए typing रोक न दे -- अगर वह delay खत्म होने से पहले एक नया keystroke आए, pending request cancel हो जाती है और timer restart होता है, तेज़ी से typing करते समय भेजी गई requests की संख्या dramatically कम करते हुए।

उदाहरण: Debouncing Search Requests

php
<?php
// JS: clearTimeout(timer); timer = setTimeout(() => search(value), 300);
echo "Debouncing happens in JavaScript before the PHP endpoint is ever called";
?>

Live Search Results Display करना

matching results के साथ AJAX response आते ही, JavaScript page के results container को update करता है -- आमतौर पर पहले किसी भी पिछले results को clear करके, फिर PHP endpoint द्वारा return किए गए हर match के लिए नए list items बनाकर।

उदाहरण: Displaying Live Search Results

php
<?php
$products = ["php", "phpunit", "phpmailer"];
echo json_encode($products);
// JS clears the results container, then builds a list item per match
?>

Out-of-Order Responses Handle करना

क्योंकि requests asynchronously fire होती हैं, एक पहले (छोटे) search term का एक slower response एक बाद के, ज़्यादा specific वाले के faster response के बाद आ सकता है -- correct, current results को stale वालों से overwrite करते हुए।

एक request identifier track करना और most recent request से अलग किसी भी response को ignore करना इससे बचाता है।

उदाहरण: Handling Out-of-Order Responses

php
<?php
$_GET['requestId'] = "3";
$_GET['q'] = "php";
echo json_encode(["requestId" => $_GET['requestId'], "results" => ["php", "phpunit"]]);
// JS ignores any response whose requestId isn't the most recent one sent
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. बिना किसी debouncing के हर single keystroke पर एक AJAX request fire करना, तेज़ी से type करने वाले user के लिए server को requests से भर देना।
  2. बिना prepared statement के live search database query बनाना, क्योंकि search term सीधे unpredictable, तेज़ी से बदलते user input से आता है।
  3. out-of-order responses handle न करना, जहाँ एक पहले, छोटे search term के लिए एक slower request एक बाद के, ज़्यादा specific के लिए एक faster request के बाद आती है, stale results दिखाते हुए।
चैप्टर सारांश
  • एक live search box keyup/input events सुनता है और हर change पर current search text के साथ एक AJAX request भेजता है।
  • Debouncing search request fire करने में तब तक देरी करती है जब तक user थोड़ी देर के लिए typing रोक न दे, हर single keystroke पर एक request से बचते हुए।
  • PHP endpoint एक prepared statement और LIKE इस्तेमाल करके search term के साथ safely database query करता है, matches को JSON की तरह return करते हुए।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.