In our previous tutorial, we have explained how to handle Image Crop and Upload using jQuery and PHP. In this tutorial, we will explain how to implement autocomplete search with Bootstrap, PHP & MySQL.
Autocomplete search or auto suggest search is a very popular feature of web applications in which suggested search list displayed based on the user entered search text just like Google instant search.
So if you’re looking for solutions to implement autosuggest search, then you’re here at right place. In this tutorial you will learn how to create autocomplete or auto Suggest search functionality using jQuery, PHP and MySQL.
In this tutorial we have used Bootstrap plugin Typeahead that’s handling autocomplete search functionality with clickable links in search result.
The tutorial is explained in very easy steps with live demo and link to download source code.
Also, read:
So let’s start the coding for autocomplete search example using Bootstrap, jQuery, PHP & MySQL. We will have following file structure for this example.
- index.php
- search.php
- profile.php
- scripts.js
Step1: Include Bootstrap and Typeahead plugin
As we are handling autocomplete search functionality using Bootstrap Typeahead plugin, so we include Bootstrap, jQuery, Typeahead files.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script> <script type="text/javascript" src="script/script.js"></script>
Step2: Create Search HTML
In index.php we will create HTML with search input to create autocomplete search.
<div class="container"> <h2>Create Autocomplete Search with Clickable Links using Typeahead Bootstrap</h2> <div class="row"> <div class="col-xs-3"> <label>Search Employee</label> <input class="typeahead form-control" type="text" placeholder="Search Employee...."> </div> </div> </div>
Step3: Handle Autocomplete with Typeahead JS
Now in scripts.js we have handled functionality to create autocomplete search using Typeahead JS Bootstrap plugin. For this we made ajax request to server side search.php to load records for the search. We have also handled functionality to create clickable link with autocomplete search result.
$( document ).ready(function() { $('input.typeahead').typeahead({ source: function (query, process) { $.ajax({ url: "search.php", type: "POST", data: 'query='+query, dataType: 'JSON', async: true, success: function(data){ var resultList = data.map(function (item) { var link = { href: item.href, name: item.emp_name }; return JSON.stringify(link); }); return process(resultList); } }) }, matcher: function (obj) { var item = JSON.parse(obj); return item.name.toLowerCase().indexOf(this.query.toLowerCase()) }, sorter: function (items) { var beginswith = [], caseSensitive = [], caseInsensitive = [], item; while (link = items.shift()) { var item = JSON.parse(link); if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item)); else if (item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item)); else caseInsensitive.push(JSON.stringify(item)); } return beginswith.concat(caseSensitive, caseInsensitive) }, highlighter: function (link) { var item = JSON.parse(link); var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>' }) }, updater: function (link) { var item = JSON.parse(link); location.href=item.href; } }); });
Step4: Get Search Result from MySQL
In search.php, we return search result in JSON format by getting from MySQL database table based on search text. We will also create link using id and passed in JSON data to create clickable link with search results.
<?php include_once("db_connect.php"); $sql = "SELECT id, employee_name as emp_name, employee_salary, employee_age FROM employee WHERE employee_name LIKE '%".$_POST['query']."%' LIMIT 20"; $resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)); $array = array(); while( $rows = mysqli_fetch_assoc($resultset) ) { $array [] = array("emp_name"=>$rows['emp_name'],"href"=>"profile.php?empid=".$rows['id']); } echo json_encode($array); ?>
Step5: Display Clicked Search Result Details
Now finally in profile.php, we have displayed details of clicked search result from MySQL database table.
<div class="container"> <h2>Employee Details</h2> <div class="row"> <div class="col-md-10"> <table width="100%" cellspacing="0" border="1"> <thead> <tr> <th> Empid</th> <th> Name</th> <th> Salary</th> <th> Age</th> </tr> <?php if(isset($_GET['empid'])) { $sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee WHERE id = '".mysql_real_escape_string($_GET['empid'])."'"; $resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)); while( $rows = mysqli_fetch_assoc($resultset) ) { ?> <tr> <td><?php echo $rows['id']; ?></td> <td><?php echo $rows['employee_name']; ?></td> <td><?php echo $rows['employee_salary']; ?></td> <td><?php echo $rows['employee_age']; ?></td> </tr> <?php } } ?> </thead> </table> </div> </div> </div>
You may also like:
- Follow and Unfollow System with PHP & MySQL
- GST Billing System with PHP & MySQL
- Restaurant Management System with PHP & MySQL
- Visitor Management System with PHP & MySQL
- Student Attendance System with PHP & MySQL
- Like and Dislike System with Ajax, PHP & MySQL
- Build Star Rating System with jQuery, PHP & MySQL
- User Registration and Login System with PHP & MySQL
- Build Contact Form with PHP and Ajax
- To-do List Application with Ajax, PHP & MySQL
- Build Event Calendar with jQuery , PHP & MySQL
- Create Dynamic Bar Chart with JavaScript, PHP & MySQL
- Drag And Drop File Upload with jQuery and PHP
- Drag and Drop Reorder with jQuery, PHP & MySQL
- Data Export to Excel with PHP and MySQL
- Multiple Image Upload with jQuery, PHP and MySQL
- Create Ajax Pagination with PHP and MySQL
- jQuery Datatables Server Side Processing with PHP & MySQL
- Editable HTML Table with jQuery, PHP & MySQL
- Filter Search Result with Ajax, PHP & MySQL
- Consuming RESTful Web Services using PHP
- Image Crop and Upload using jQuery and PHP
- Live Datatables CRUD with Ajax, PHP & MySQL
- Create REST API with PHP & MySQL
- Build Dynamic Image Gallery with PHP & MySQL
- Implement jQuery Bootgrid with PHP & MySQL
You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download
I love this. so helpful.
But how do i show more employee details in the suggestion list.
Example: employee name(employee id)
You can customize to display result according to your needs. Thanks!
This is very useful, thank you
One thing which I can’t work out is that its not working where the query begins with the first letter of the employee. If you type G then you would expect Garrett to come up – it doesn’t. If you type a it does.
Any ideas?
I am checking this and update you soon. thanks!
Great code!
One question. Do you know why is not possible to search by the first letter of the word (upper case).
Take a look into the demo. Try to search for G, H, R, etc. Only find words with this letter in lower. Never get the first letter.
Thanks!
How can I create the dropdown-menu with the search result as you have in the demo?
You can easily create dropdown menu with search result using bootstrap.
I am checking this and update you. thanks!
Hi. It’s a very nice function but doesn’t work. What’s happened?
Hi,
Thanks for this code!
Why is not possible to search by the first letter of the word ?
Thanks
checking this and update you, thanks!
its working, what issue you’re facing?