Autocomplete search filter display suggestion based on the user input e.g. listing all products which start with character ‘a’.
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
- CSS
- PHP
- jQuery
- Conclusion
Make Autocomplete Search with jQuery AJAX
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
- CSS
- PHP
- jQuery
- Demo
- Conclusion
1. Table structure
I am usinguser
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 newconfig.php
file.
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
Creating an input element and for displaying suggestion list I am using an unordered list<ul id='searchResult'>
.Displaying the user detail according to selection in
<div id='userDetail'>
.
Completed Code
<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>
4. CSS
.clear{ clear:both; margin-top: 20px; } #searchResult{ list-style: none; padding: 0px; width: 250px; position: absolute; margin: 0; } #searchResult li{ background: lavender; padding: 4px; margin-bottom: 1px; } #searchResult li:nth-child(even){ background: cadetblue; color: white; } #searchResult li:hover{ cursor: pointer; } input[type=text]{ padding: 5px; width: 250px; letter-spacing: 1px; }
5. PHP
Create a new filegetSearch.php
from here 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.
include "config.php"; $type = $_POST['type']; // Search result if($type == 1){ $searchText = $_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 = $_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
Whenkeyup
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. Conclusion
Attachkeyup
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 AJAX request code in
setText()
method.If you found this tutorial helpful then don't forget to share.
0 Comments:
Post a Comment