Autocomplete search filter display suggestion based on the user input e.g. listing all products which start with the character ‘a’.
It makes easier for the user to search for an item from the list and select it from the suggestion list.
Require jQuery AJAX for implementing this.
Whenever the user enters a character send an AJAX request to fetch records with PHP and display the result.
In the demonstration, I show a textbox to search users. When an item selected from the suggestion list then fetch details of the selected users and display on the screen.
Contents
- Table structure
- Configuration
- HTML – Create Autocomplete search Layout
- CSS
- PHP – Fetch suggestion list
- jQuery
- Demo
- Conclusion
1. Table structure
I am using user
table in the example.
CREATE TABLE `user` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a config.php
file for the database configuration.
Completed Code
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. HTML – Create Autocomplete search Layout
Create a <div class='autocomplete'>
. In the <div >
create a textbox and for displaying suggestion list on input create <ul id='searchResult'>
element.
Display the user detail according to selection in <div id='userDetail'>
.
Completed Code
<div class='autocomplete'> <div>Enter Name </div> <div> <input type="text" id="txt_search" name="txt_search"> </div> <ul id="searchResult"></ul> <div class="clear"></div> <div id="userDetail"></div> </div>
4. 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: #F2F3F4; padding: 4px; margin-bottom: 1px; } .autocomplete #searchResult li:nth-child(even){ background: #E5E7E9; color: black; } .autocomplete #searchResult li:hover{ cursor: pointer; background: #CACFD2; } .autocomplete input[type=text]{ padding: 5px; width: 100%; letter-spacing: 1px; }
5. PHP – Fetch suggestion list
Create getSearch.php
file for handling AJAX request and send the response.
- If $type == 1 – Search for the name in the
user
table and initialize the$search_arr
array with the records. Return a JSON value. - If $type == 2 – Fetch user details by id from the
user
table and return JSON value.
Completed Code
include "config.php"; $type = 0; if(isset($_POST['type'])){ $type = $_POST['type']; } // Search result if($type == 1){ $searchText = mysqli_real_escape_string($con,$_POST['search']); $sql = "SELECT id,name FROM user where name like '%".$searchText."%' order by name asc limit 5"; $result = mysqli_query($con,$sql); $search_arr = array(); while($fetch = mysqli_fetch_assoc($result)){ $id = $fetch['id']; $name = $fetch['name']; $search_arr[] = array("id" => $id, "name" => $name); } echo json_encode($search_arr); } // get User data if($type == 2){ $userid = mysqli_real_escape_string($con,$_POST['userid']); $sql = "SELECT username,email FROM user where id=".$userid; $result = mysqli_query($con,$sql); $return_arr = array(); while($fetch = mysqli_fetch_assoc($result)){ $username = $fetch['username']; $email = $fetch['email']; $return_arr[] = array("username"=>$username, "email"=> $email); } echo json_encode($return_arr); }
6. jQuery
When keyup
event trigger on search textbox then send AJAX request where passing search: search, type: 1
as data
.
On AJAX successful callback loop on the response.
Create <li >
and append in the <ul>
and bind click
event on the $('#searchResult li')
.
To get the details of a selected user from the suggestion list send an AJAX request where pass userid:userid, type:2
as data
and display the response in <div id='userDetail'>
on successful callback.
$(document).ready(function(){ $("#txt_search").keyup(function(){ var search = $(this).val(); if(search != ""){ $.ajax({ url: 'getSearch.php', type: 'post', data: {search:search, type:1}, dataType: 'json', success:function(response){ var len = response.length; $("#searchResult").empty(); for( var i = 0; i<len; i++){ var id = response[i]['id']; var name = response[i]['name']; $("#searchResult").append("<li value='"+id+"'>"+name+"</li>"); } // binding click event to li $("#searchResult li").bind("click",function(){ setText(this); }); } }); } }); }); // Set Text to search box and get details function setText(element){ var value = $(element).text(); var userid = $(element).val(); $("#txt_search").val(value); $("#searchResult").empty(); // Request User Details $.ajax({ url: 'getSearch.php', type: 'post', data: {userid:userid, type:2}, dataType: 'json', success: function(response){ var len = response.length; $("#userDetail").empty(); if(len > 0){ var username = response[0]['username']; var email = response[0]['email']; $("#userDetail").append("Username : " + username + "<br/>"); $("#userDetail").append("Email : " + email); } } }); }
7. Demo
8. Conclusion
Attach keyup
event on the input element to get the suggestion list when entering some value.
If you don’t want to fetch the details according to selection for this just remove the AJAX request code in setText()
function.