Javascript Autocomplete textbox helps the user to pick an item from the suggestion list based on the input. It occupies less space on the page. It’s designed to give you a smooth experience while using minimal space on your webpage, making your interface look neat and organized.
Data is not preloaded on the page. Instead, it dynamically loads data using AJAX as soon as the user starts typing.
In this tutorial, I show how you can create autocomplete textbox with MySQL database data using JavaScript and PHP.

Table of Content
- Create a Table
- Database Connection
- Creating Autocomplete Layout in HTML
- PHP Code for Handling AJAX Requests and Returning Autocomplete Data
- Implementing JavaScript Autocomplete Functionality
- Demo
- Conclusion
1. Create a Table
I am using users table in the example. It has the following structure –
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL, `city` varchar(80) NOT NULL );
2. Database Connection
Create a config.php file for database configuration.
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = "root"; /* Password */
$dbname = "tutorial"; /* Database name */
// Create connection
$con = new mysqli($host, $user, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
3. Creating Autocomplete Layout in HTML
Within the HTML, we create a text input field to facilitate searching. The onkeyup event is attached to this input field, which triggers the searchResult() function as users type. This function will be responsible for displaying the suggestions dynamically.
To present the suggestions, we utilize an unordered list (<ul>) with the searchResult id. This list will be populated with the suggested names as users input their search queries.
Furthermore, we include a <div> element with the userDetail id to display details about the selected user from the suggestion list.
<style type="text/css">
.clear{
clear:both;
margin-top: 20px;
}
.autocomplete{
width: 250px;
position: relative;
}
.autocomplete #searchResult{
list-style: none;
padding: 0px;
width: 100%;
position: absolute;
margin: 0;
background: white;
}
.autocomplete #searchResult li{
background: #F1F4FFFF;
padding: 4px;
margin-bottom: 1px;
}
.autocomplete #searchResult li:nth-child(even){
background: #A2A2A1FF;
color: white;
}
.autocomplete #searchResult li:hover{
cursor: pointer;
}
.autocomplete input[type=text]{
padding: 5px;
width: 100%;
letter-spacing: 1px;
}
</style>
<div class='autocomplete'>
<div>Search Name </div>
<div>
<input type="text" id="txt_search" onkeyup="searchResult(this.value);">
</div>
<!-- Suggestion List -->
<ul id="searchResult"></ul>
<div class="clear"></div>
<!-- Show selected user Details -->
<div id="userDetail"></div>
</div>
4. PHP Code for Handling AJAX Requests and Returning Autocomplete Data
Create ajaxfile.php file to handle AJAX requests and retrieve autocomplete data from the MySQL database.
From here handle 2 requests –
- suggestionList – Return records based on search value for displaying suggestion list.
- userdetails – Return user details of the selected user from the suggestion list.
Handling “suggestionList” Request:
- Read the POST data sent by the front-end, specifically looking for the
searchvalue. - Then store the search value in the
$searchvariable. - Next, initialize an empty array named
$return_arrto hold the autocomplete suggestions. - If the search value is not empty, we perform a SQL query to the database using the
"LIKE"operator, fetching up to five records from theuserstable where the name field partially matches the search value. - Loop through the fetched records and add each user’s id and name to the
$return_arrarray. - Finally, encode the
$return_arrarray into JSON format and send it back to the front-end.
Handling “userdetails” Request:
- Read the POST data to check if the
useridvalue is present. - If the
useridis available, assign it to the$useridvariable. - Initialize an empty array named
$datato hold the user details. - The
$statusvariable is set to 0 by default. - If the
$useridis a valid numeric value greater than 0, we perform a SQL query to retrieve the user’s details from theuserstable based on the provided id. - Loop through the fetched record, collecting the id, name, email, and city into the
$dataarray. - Set
$statusto 1 to indicate a successful retrieval of user details. - The
$dataand$statusvariables are combined into the$responsearray. - Finally, encode the
$responsearray into JSON format and send it back to the front-end.
<?php
include "config.php";
// Read POST data
$postData = json_decode(file_get_contents("php://input"));
$request = "";
if(isset($postData->request)){
$request = $postData->request;
}
// Search result
if($request == 'suggestionList'){
$search = "";
if(isset($postData->search)){
$search = trim($postData->search);
}
$return_arr = array();
if(!empty($search)){
$search = mysqli_real_escape_string($con,$search);
$sql = "SELECT id,name FROM users where name like '%".$search."%' order by name asc limit 5";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
$return_arr[] = array("id" => $id, "name" => $name);
}
}
echo json_encode($return_arr);
die;
}
// Get User data by ID
if($request == 'userdetails'){
$userid = 0;
if(isset($postData->userid)){
$userid = $postData->userid;
}
$data = array();
$status = 0;
if(is_numeric($userid) && $userid > 0){
$userid = mysqli_real_escape_string($con,$userid);
$sql = "SELECT * FROM users where id=".$userid;
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
$email = $row['email'];
$city = $row['city'];
$data = array(
"id" => $id,
"name" => $name,
"email" => $email,
"city" => $city,
);
$status = 1;
}
}
$response = array(
'status' => $status,
'data' => $data
);
echo json_encode($response);
die;
}
5. Implementing JavaScript Autocomplete Functionality
Write a JavaScript code for enabling autocomplete and handling AJAX requests to fetch autocomplete data from the PHP backend.
Create 2 functions –
- searchResult
- get_userdetails
searchResult() Function:
- This function is called when the user types in the search box.
- If search variable value is not empty then send AJAX POST request to
ajaxfile.phpfile. Here, pass{request: 'suggestionList',search: search}as data. - Upon receiving a successful response, parse the JSON data and retrieves the suggestions.
- It then dynamically populates the suggestion list
(<ul id="searchResult">)with<li>elements containing the suggested names. - Each suggestion is made clickable, and a click event listener is added to fetch user details when the user selects a suggestion.
get_userdetails() Function
- This function is called when the user clicks on a suggestion from the autocomplete list.
- It reads the selected item’s value and text (user ID and name).
- The suggestion list
(<ul id="searchResult">)and the user details section(<div id="userDetail">)are then emptied to prepare for the updated information. - The search box text is set to the selected item’s name to provide visual feedback to the user.
- Send AJAX POST request to
ajaxfile.phpfile. Here, pass{request: 'userdetails',userid: userid}asdata. - Upon receiving a successful response, parse the JSON data and extracts user details.
- The user details, including ID, name, email, and city, are displayed in separate
<p>elements and appended to the user details section(<div id="userDetail">).
// Search results
function searchResult(search){
if(search.length > 0){
// AJAX request
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = JSON.parse(this.responseText);
var len = 0;
if(response != null){
len = response.length;
}
if(len > 0){
// <ul id="searchResult"> element
var searchResult = document.getElementById('searchResult');
// Empty the search result
searchResult.innerHTML = "";
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
// Add <li > to searchResult
var liel = document.createElement('li');
liel.value = id;
liel.innerHTML = name;
// Add click event to fetch details on click
liel.addEventListener('click', get_userdetails);
searchResult.appendChild(liel);
}
}
}
};
var data = {request: 'suggestionList',search: search};
xhttp.send(JSON.stringify(data));
}else{
document.getElementById('searchResult').innerHTML = "";
}
}
// Get clicked item Data
function get_userdetails(evt){
// Read clicked <li > value and text
var userid = evt.currentTarget.value;
var text = evt.currentTarget.innerText;
// Empty the search result and user Details
document.getElementById('searchResult').innerHTML = "";
document.getElementById('userDetail').innerHTML = "";
// Update searchbox text with selected item
document.getElementById('txt_search').value = text;
// AJAX request
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = JSON.parse(this.responseText);
// Check status
if(response.status == 1){
// Read user data
var data = response.data;
var id = data.id;
var name = data.name;
var email = data.email;
var city = data.city;
// <div id="userDetail"> element
var userDetail = document.getElementById('userDetail');
// Append <p > element to <div id="userDetail">
// ID
var para_id = document.createElement('p');
para_id.innerHTML = 'ID : ' + id;
userDetail.appendChild(para_id);
// Name
var para_name = document.createElement('p');
para_name.innerHTML = 'NAME : ' + name;
userDetail.appendChild(para_name);
// Email
var para_email = document.createElement('p');
para_email.innerHTML = 'EMAIL : ' + email;
userDetail.appendChild(para_email);
// City
var para_city = document.createElement('p');
para_city.innerHTML = 'City : ' + city;
userDetail.appendChild(para_city);
}
}
};
var data = {request: 'userdetails',userid: userid};
xhttp.send(JSON.stringify(data));
}
6. Demo
7. Conclusion
I showed how you can create autocomplete search box using JavaScript, PHP, and MySQL.
The example demonstrated here loads a maximum of 5 records in the search result, but you have the flexibility to adjust this value to suit your project’s requirements.
If you encounter any issues with the data not loading, make sure to review the code carefully. Utilizing the browser’s network tab can be incredibly helpful for debugging and identifying any potential errors.
For those interested in a jQuery version of this tutorial, we have provided an alternative implementation that you can explore for additional insights.
If you found this tutorial helpful then don't forget to share.