Autocomplete Textbox using PHP, MySQL and AJAX

As all of us know that autocomplete textbox is one of the most user friendly web elements. It makes searching easy. You must have seen autosuggestion and autocomplete textbox on google, facebook etc. Now I amd going to explain, how it is implemented using PHP, MySQL and jQuery. It can be implemented using jQeury AJAX. But here, I am going to explain the simplest way. So lets start with the autocomplete textbox tutorial.
In this tutorial I am going to use simple autocomplete function. Here I will display a textbox for coding skills entry. Once you start entering skill, the autosuggestion skills would be listed under the textbox and you can select it from there.
JQUERY UI LIBRARY & JQUERY
We need to include jQuery library, jQuery UI library and jQuery UI stylesheet.
1
2
3
|
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
|
Define the autocomplete function and provide the source file.
1
2
3
4
5
|
$(document).ready(function() {
$( "#codingSkills" ).autocomplete({
source: 'search.php'
});
});
|
HTML
Now, enter following HTML:
1
2
3
4
|
<div class="main">
<label for="codingSkills">Coding Skill: </label>
<input id="codingSkills"><br>
</div>
|
PHP
Now, for getting data from database PHP code is needed. The textbox value will be get by term field ( $_GET[‘term’] ) from the query string. Now we will fetch the data from skills table and filtering the skills by $_GET[‘term’] . At last we will return the filtered skills data in JSON format. Here is the PHP source code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '123';
$dbName = 'test';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
//return json data
echo json_encode($data);
?>
|
That’s all folks. Now you are all set to use autocomplete textbox.
You can download the source code from here.
