PHP AJAX Autocomplete Tutorial

PHP AJAX Autocomplete Tutorial – Complete Beginner Guide

Autocomplete improves user experience by suggesting possible values as users type in an input field. It is commonly used in search boxes, form inputs, city selection, email suggestions, and product names.

This tutorial explains how to build a PHP AJAX autocomplete system using MySQL, with clear examples and output.


What Is Autocomplete in PHP AJAX?

Autocomplete is a feature where:

  • User types in an input field
  • AJAX sends the typed value to PHP
  • PHP fetches matching data from MySQL
  • Suggestions appear below the input field
  • Page does not reload

Why Use AJAX Autocomplete?

Autocomplete helps to:

  • Improve form usability
  • Reduce typing errors
  • Speed up data entry
  • Enhance user experience

Technologies Used in PHP AJAX Autocomplete

  • HTML for input field
  • JavaScript for AJAX requests
  • PHP for server-side processing
  • MySQL for suggestion data

Prerequisites for Autocomplete Tutorial

Before starting, you should know:

  • Basic HTML
  • Basic JavaScript
  • PHP fundamentals
  • MySQL SELECT and LIKE

Sample MySQL Table Used for Autocomplete

CREATE TABLE cities (
    id INT AUTO_INCREMENT PRIMARY KEY,
    city_name VARCHAR(100)
);

PHP MySQL Database Connection File

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");

if (!$conn) {
    die("Database connection failed");
}
?>

Step 1: Create HTML Input Field

<!DOCTYPE html>
<html>
<head>
    <title>PHP AJAX Autocomplete</title>
    <style>
        #suggestions {
            border: 1px solid #ccc;
            max-width: 300px;
        }
        .item {
            padding: 5px;
            cursor: pointer;
        }
        .item:hover {
            background-color: #f0f0f0;
        }
    </style>

    <script>
        function getSuggestions(value) {
            if (value.length == 0) {
                document.getElementById("suggestions").innerHTML = "";
                return;
            }

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

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("suggestions").innerHTML = xhr.responseText;
                }
            };

            xhr.send();
        }

        function selectValue(value) {
            document.getElementById("search").value = value;
            document.getElementById("suggestions").innerHTML = "";
        }
    </script>
</head>
<body>

<input type="text" id="search" onkeyup="getSuggestions(this.value)" placeholder="Enter city name">
<div id="suggestions"></div>

</body>
</html>

Step 2: Create PHP Autocomplete Script (autocomplete.php)

<?php
include "db.php";

$keyword = $_GET['query'];

$sql = "SELECT city_name FROM cities WHERE city_name LIKE '%$keyword%' LIMIT 5";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {
    echo "<div class='item' onclick=\"selectValue('".$row['city_name']."')\">";
    echo $row['city_name'];
    echo "</div>";
}
?>

Output While Typing “del”

Delhi

Typing “mu”:

Mumbai

Suggestions appear instantly below the input field.


Secure Autocomplete Using Prepared Statement

<?php
include "db.php";

$stmt = mysqli_prepare($conn,
    "SELECT city_name FROM cities WHERE city_name LIKE ? LIMIT 5");
$search = "%" . $_GET['query'] . "%";
mysqli_stmt_bind_param($stmt, "s", $search);

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

while ($row = mysqli_fetch_assoc($result)) {
    echo "<div class='item'>".$row['city_name']."</div>";
}
?>

Difference Between Live Search and Autocomplete

FeatureLive SearchAutocomplete
Displays full resultsYesNo
Suggests valuesNoYes
Input focusOptionalRequired
UsageSearch pagesForms
PHP AJAX autocomplete, PHP autocomplete tutorial, AJAX input suggestion PHP, PHP MySQL autocomplete, PHP AJAX autocomplete example

Common Mistakes in Autocomplete Implementation

  • No result limit
  • Missing input validation
  • Not hiding suggestion box
  • Poor UI styling

Best Practices for PHP AJAX Autocomplete

  • Use LIMIT to restrict results
  • Use prepared statements
  • Add indexes on searchable columns
  • Hide suggestions when empty
  • Improve UX with CSS

Related tutorial


Frequently Asked Questions (FAQ)

1. What is autocomplete in PHP?

It suggests values while the user types.

2. Does autocomplete reload the page?

No, it works asynchronously.

3. Is autocomplete secure?

Yes, with prepared statements.

4. Can autocomplete work without database?

Yes, with static data.

5. Is autocomplete good for forms?

Yes, especially for large datasets.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Prove your humanity: 4   +   2   =