Make Autocomplete search with jQuery AJAX

Autocomplete search element show suggestion based on user input e.g. listing all products which start with character ‘a’.

For implementing this in the program you need to send AJAX when a keyup event triggers on an input element.

What in the demonstration?

Show an input box for searching users and show the list of the result based on input. When the users select any of the items from the suggestion list then fetch details of the selected value and display it on the screen.

Make Autocomplete search with jQuery AJAX


Contents

  1. Configuration
  2. HTML
  3. CSS
  4. PHP
  5. jQuery
  6. Conclusion

 


1. Configuration

Create a new config.php and setup database connection.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysql_connect($host, $user, $password) or die("Unable to connect");

// selecting database
$db = mysql_select_db($dbname, $con) or die("Database not found");

2. HTML

Creating an input element and for displaying suggestion list I am using 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>

3. 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;
}

4. PHP

Create a new file getSearch.php from here handling AJAX request and send the response.

  • If $type value is 1 – fetch the users name from MySQL table based on search value and return a JSON value.
  • If $type value is 2 –  fetch the user details and return a 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 = mysql_query($sql);

    $search_arr = array();

    while($fetch = mysql_fetch_array($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 = mysql_query($sql);

    $return_arr = array();
    while($fetch = mysql_fetch_array($result)){
        $username = $fetch['username'];
        $email = $fetch['email'];

        $return_arr[] = array("username"=>$username, "email"=> $email);
    }

    echo json_encode($return_arr);
}

5. jQuery

When keyup event trigger on search textbox then send AJAX request to above-created file PHP file where passing search value and type.

Bind click event to suggestion list after creating suggestion list when AJAX return successfully.

For getting the details of selected user I again send an AJAX request and display the response in <div id='userDetail'>.

$(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);
            }
        }

    });
}

6. Conclusion

In this tutorial, I showed how you can show autocomplete search while entering input. If you don’t want to fetch the details according to selection for this just remove AJAX request code in setText() method.

Spread the love

Related Post

Be First to Comment

Leave a Reply

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