PHP Example – AJAX Live Search

Welcome to The Coding College! In this tutorial, we’ll show you how to implement a live search feature using AJAX and PHP. Live search allows users to see search results instantly as they type without reloading the webpage. This feature enhances user experience and improves website interactivity.


What is AJAX Live Search?

  • Live search dynamically fetches and displays search results as the user types.
  • AJAX sends a request to the server in the background and retrieves data without a page reload.
  • PHP processes the query and retrieves matching results from the database.

Example Overview

We will:

  1. Create a MySQL database to store data.
  2. Write a PHP script to search the database based on user input.
  3. Use AJAX to send user queries to the PHP script.
  4. Display the search results dynamically in the browser.

Step 1: Set Up the MySQL Database

Create a table in your MySQL database to store sample data.

SQL Script to Create Table

CREATE DATABASE live_search_demo;

USE live_search_demo;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL
);

INSERT INTO users (name, email) VALUES
('John Doe', '[email protected]'),
('Jane Smith', '[email protected]'),
('Mark Taylor', '[email protected]'),
('Emma Johnson', '[email protected]'),
('William Brown', '[email protected]');

Step 2: Create the HTML Page

This page contains an input box for the search query and a div to display results.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Live Search Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        input {
            width: 300px;
            padding: 8px;
            margin-bottom: 10px;
        }
        .results {
            border: 1px solid #ccc;
            max-width: 300px;
            padding: 10px;
            display: none;
        }
        .results p {
            margin: 5px 0;
            cursor: pointer;
        }
        .results p:hover {
            background-color: #f1f1f1;
        }
    </style>
    <script>
        function liveSearch() {
            var query = document.getElementById("searchBox").value;
            var resultsDiv = document.getElementById("results");

            if (query.length == 0) {
                resultsDiv.innerHTML = "";
                resultsDiv.style.display = "none";
                return;
            }

            var xhr = new XMLHttpRequest();
            xhr.open("GET", "live_search.php?q=" + query, true);

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    resultsDiv.style.display = "block";
                    resultsDiv.innerHTML = xhr.responseText;
                }
            };

            xhr.send();
        }
    </script>
</head>
<body>
    <h1>AJAX Live Search Example</h1>
    <p>Start typing to search for a user:</p>
    <input type="text" id="searchBox" onkeyup="liveSearch()" placeholder="Search for a name..." />
    <div id="results" class="results"></div>
</body>
</html>

Explanation

  1. Input Field: Captures user input and triggers the liveSearch() function on every keystroke using the onkeyup event.
  2. AJAX Request: The function sends an HTTP GET request to the live_search.php script, passing the search query.
  3. Results Div: The server’s response is displayed dynamically inside the results div.

Step 3: PHP Script to Handle the Search Query

Create a PHP file called live_search.php to process the search query and return matching results.

<?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "live_search_demo";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve the query parameter
if (isset($_GET['q'])) {
    $query = $_GET['q'];

    // Prepare and execute the SQL statement
    $sql = "SELECT name, email FROM users WHERE name LIKE ?";
    $stmt = $conn->prepare($sql);
    $searchTerm = "%$query%";
    $stmt->bind_param("s", $searchTerm);
    $stmt->execute();
    $result = $stmt->get_result();

    // Output the search results
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<p>" . htmlspecialchars($row['name']) . " - " . htmlspecialchars($row['email']) . "</p>";
        }
    } else {
        echo "<p>No results found</p>";
    }

    $stmt->close();
}

$conn->close();
?>

Explanation

  1. Database Connection: Connects to the MySQL database.
  2. GET Query Parameter: Captures the search input sent by the AJAX request.
  3. Prepared Statement: Queries the database for matching names using the LIKE operator.
  4. Dynamic Results: Outputs matching results as HTML paragraphs.

How It Works

  1. The user starts typing in the search box.
  2. The onkeyup event triggers the liveSearch() JavaScript function.
  3. An AJAX request is sent to live_search.php with the query string.
  4. The PHP script queries the database and returns the results.
  5. The results are dynamically displayed under the search box without refreshing the page.

Output

When you type in the search box, matching results appear dynamically:

Search: John
-------------------
John Doe - [email protected]

Typing “J” would dynamically fetch all results starting with “J”, like:

Jane Smith - [email protected]
John Doe - [email protected]

Benefits of AJAX Live Search

  1. Faster User Experience: Instant results without reloading the page.
  2. Efficient: Fetches only relevant data from the server.
  3. Dynamic: Results update in real-time as the user types.

Conclusion

In this tutorial, we implemented a live search feature using AJAX and PHP. This technique improves user experience by dynamically displaying search results without reloading the webpage.

Next Steps:

  • Enhance this feature by adding highlighting for matched text.
  • Implement a throttle or debounce function to limit AJAX calls for large inputs.
  • Display results with additional details, such as images or links.

Leave a Comment