Make Autocomplete Search with jQuery AJAX

Autocomplete search filter display suggestion based on the user input e.g. listing all products which start with 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.

Make Autocomplete search with jQuery AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. CSS
  5. PHP
  6. jQuery
  7. Demo
  8. 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 new config.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 class="container">
    <h1>jQuery Autocomplete Search</h1>
    <div id="div_content">

        <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>
</div>

4. CSS

.container{
 border:1px solid darkgrey;
 border-radius:3px;
 padding:5px;
 width:40%;
 margin:0 auto;
 letter-spacing:1px;
 font-family: sans-serif;
 box-shadow: 0px 2px 2px 0px gray;
}

.container h1{
 margin-top: 0px;
 font-weight: normal;
 padding: 10px;
 background-color: cornflowerblue;
 color: white;
 font-family: sans-serif;
 text-align: center;
}

#div_content{
 width:60%;
 margin: 0 auto;
 min-height:200px;
 height: auto;
}

#div_content div{
 margin-bottom:8px;

}
.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 file getSearch.php from here handling AJAX request and send the response.

  • If $type == 1 – Search for the name in the user table and intialize 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 = $_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

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 fname = response[i]['fname'];

                        $("#searchResult").append("<li value='"+id+"'>"+fname+"</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

Input some characters in the textbox.


8. Conclusion

Attach keyup event on the input element to get 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.
Spread the love
  •  
  • 1
  •  
  •  
  •  
  •  

6 Comments

  1. Pieter said:

    Where i can find the type? I not see aby type input hidden in html…

    February 28, 2018
    Reply
    • Yogesh Singh said:

      Hi Pieter,
      If you are saying about $_POST[‘type’] in getSearch.php then it is pass from $.ajax request in jQuery to know the type of request.

      There is no HTML element with name=’type’.

      February 28, 2018
      Reply
  2. Jose said:

    Hi! Thanks for the code. It served me a lot.

    Just a question:

    when I search my database, most of the time is goes well, however, in some searches I do not see any results, especially when I search with words of 2 and 3 characters.

    Is there any way to force the search from writing the first character?

    Thanks in advance.

    April 12, 2018
    Reply
  3. Harshada said:

    How will I display fetch data on new page after selecting name. Need urgent.

    April 20, 2018
    Reply
    • Yogesh Singh said:

      Hi Harshada,
      You can use setText() function which I called after selecting an option from the list in the example. You can pass the value to the URL while redirecting to a new page and use the value.

      April 20, 2018
      Reply
      • Harshada said:

        Can you please provide me the code? As I have already did that…

        April 21, 2018
        Reply

Leave a Reply

Your email address will not be published. Required fields are marked *