We have created full functional demo to view autosuggest functionality and also can download demo files to easily implement in your project.
So let’s start the coding
Step 1: First we will include bootstrap, jQuery and Typehead files into head section of page.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
Step 2: Now we will create HTML with search input using Bootstrap.
<div class="container">
<h2>Autocomplete Search with Bootstrap Typeahead</h2>
<div class="row">
<div class="col-xs-2">
<br/>
<label>Search Name</label>
<input class="typeahead form-control" type="text" placeholder="Search Name....">
</div>
</div>
</div>
Step 3: Now we will handle functionality to make ajax request to search_data.php to get JSON data to display using Typehead JS.
$( document ).ready(function() {
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get('search_data.php', { query: query }, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
showHintOnFocus:'all'
});
});
Step 4: Now in PHP script search_data.php, we will make connection to MySQL database and get records from employee table. We will store employee names in an array and returned as json using function json_encode as Typehead js plugin needs data in JSON format to display autosuggest data list.
<?php
$servername = "localhost";
$username = "root";
$password = "12345";
$dbname = "demos";
$sql = "SELECT employee_name FROM employee WHERE employee_name LIKE '%".$_GET['query']."%' LIMIT 20";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$json = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$json[] = $rows["employee_name"];
}
echo json_encode($json);
?>
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]