Make Autocomplete Search with jQuery AJAX

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.

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

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

View 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() method.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

13 thoughts on “Make Autocomplete Search with jQuery AJAX”

    • 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’.

      Reply
  1. 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.

    Reply
  2. Hi
    Great.. you saved my time
    small correction while rendering the search result
    threre’s small change
    replace fname with name (var fname = response[i][‘name’];)
    because you have created same in DB

    Reply
  3. Thanks for the example, works great!
    The only problem I have is making it work with multiple text fields. When using ID attribute it breaks even though I gave unique ID names.
    Any ideas how I can make this work?

    Reply

Leave a Comment