Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 49

AJAX Live Search in PHP

In this lesson: Show search results while typing using PHP, MySQL and AJAX (fetch) — secure LIKE query and full working code.

What we are building

A live search shows results the moment you type, without pressing a button or reloading the page. It combines three pieces: an HTML search box, some JavaScript using AJAX, and a PHP file that queries the database. This is one of the most popular real features to learn.

💡 AJAX = the page quietly asks the server for data and updates just one part, with no full reload.

How AJAX works

  1. The user types in the search box.
  2. JavaScript sends the typed text to a PHP file with fetch().
  3. PHP searches the database and returns matching results.
  4. JavaScript places those results into a box on the page — instantly.

The page never reloads; only the results area changes. That is what makes it feel fast and modern.

The search box and JS

<input type="text" id="search" placeholder="Search...">
<div id="results"></div>

<script>
  const box = document.getElementById("search");
  box.addEventListener("input", function () {
      fetch("search.php?q=" + encodeURIComponent(box.value))
          .then(res => res.text())
          .then(html => {
              document.getElementById("results").innerHTML = html;
          });
  });
</script>

On every keystroke (input), JavaScript sends the text to search.php and drops the reply into the results div. encodeURIComponent makes the text safe for the URL.

The PHP handler

<?php
  // search.php
  $q = $_GET["q"] ?? "";
  $stmt = $pdo->prepare(
      "SELECT name FROM students WHERE name LIKE ?"
  );
  $stmt->execute(["%$q%"]);
  foreach ($stmt->fetchAll() as $row) {
      echo "<p>" . htmlspecialchars($row["name"]) . "</p>";
  }
?>
<p>Aman</p> <p>Amit</p>

The handler reads q, runs a prepared statement with LIKE to find matches, and echoes safe HTML that JavaScript displays.

Keeping it safe

  • Prepared statement: bind the search term, never paste it into SQL.
  • Escape output: wrap results in htmlspecialchars to block XSS.
  • Debounce: wait a moment after typing stops, so you do not hit the server on every letter.
  • Skip tiny queries: ignore searches shorter than 2 characters.

Common mistakes

  • Pasting the search term into SQL. Use a prepared statement with LIKE ?.
  • Not escaping results. Un-escaped names can carry XSS — use htmlspecialchars.
  • Searching on every keystroke. Add a debounce delay to avoid flooding the server.
  • Forgetting encodeURIComponent. Special characters break the URL without it.

Summary

  • Live search updates results as you type, with no page reload.
  • AJAX (via fetch) sends the text to PHP and shows the reply.
  • PHP uses a prepared statement with LIKE to find matches.
  • Escape output and use a debounce for safety and speed.
  • No jQuery needed — modern fetch is enough.

Next, secure the query side with prepared statements, or return structured data with PHP JSON.

Frequently Asked Questions

What is AJAX in simple words?
AJAX lets a web page talk to the server in the background and update part of the page without a full reload. For a live search, it sends what you typed to PHP and shows the results instantly, all without refreshing.
How does live search work?
As the user types, JavaScript sends the text to a PHP file with fetch(). The PHP queries the database and returns matching results, which JavaScript drops into a results box — all in real time.
Do I need jQuery for AJAX?
No. Modern JavaScript has the built-in fetch() function, which is clean and needs no library. jQuery's $.ajax also works, but fetch is the standard modern way.
How do I keep live search safe from SQL injection?
Use a prepared statement in the PHP handler and bind the search term as a parameter. Never paste the typed text straight into the SQL query. Also escape output with htmlspecialchars.
Why does my live search feel slow or spammy?
Firing a request on every keystroke can overload the server. Add a short delay (debounce) so it only searches after the user pauses typing, and ignore very short queries.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicCAPTCHA Validation Your progress: 49 / 50 (98%) · Lesson 50 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free