PHP - AJAX Live Search

Creating an AJAX live search feature in PHP involves allowing users to search for data in a database in real-time as they type, without needing to reload the page. Here's a step-by-step guide on how to implement an AJAX live search using HTML, JavaScript, and PHP:


1. HTML (index.html):

Create an HTML page with a search input field that users will interact with. The search results will be displayed dynamically using AJAX.

html
<!DOCTYPE html>
<html>
    <head>
        <title>AJAX Live Search Example</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
                $("#search").on("keyup", function() {
                var searchText = $(this).val();
                    if (searchText !== "") {
                        $.ajax({
                            type: "GET",
                            url: "search.php",
                            data: { query: searchText },
                            success: function(response) {
                                $("#search-results").html(response);
                            }
                        });
                    } else {
                        $("#search-results").empty();
                    }
                });
            });
        </script>
    </head>
    <body>
        <h2>Live Search</h2>
        <input type="text" id="search" placeholder="Search...">
        <div id="search-results">
            <!-- Search results will be displayed here -->
        </div>
    </body>
</html>

2. PHP (search.php):

Create a PHP script that handles the search query and returns the matching results based on user input.

php
<?php
// Assuming you have a database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

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

if (isset($_GET['query'])) {
    $query = $_GET['query'];

    // Perform a search query on the database
    $sql = "SELECT * FROM products WHERE product_name LIKE '%$query%'";
    $result = $conn->query($sql);

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

$conn->close();
?>

3. Database Table (products):

Create a database table named "products" with relevant columns that you want to search through.

sql
CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    // Add more columns as needed
);
INSERT INTO products (product_name) VALUES ('Product A'), ('Product B'), ('Product C');

In this example, as users type in the search input field, the `keyup` event triggers an AJAX GET request to the `search.php` script. The PHP script searches the database for products that match the user's query and returns the results, which are then displayed in the `search-results` div.


Ensure you have proper error handling, input validation, and security measures in place to prevent SQL injection or other vulnerabilities.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext