How to Create A auto-complete searching with Jquery, AJAX and PHP

How to Create A auto-complete search with Jquery, AJAX, and PHP

 

In this post, you will learn How to autocomplete textbox using jQuery AJAX in PHP MySQL.The Ajax Autocomplete text box is very user-friendly for any website.

The Autocomplete text box allows users to quickly find and select values from a list of pre-populated options. Suggestions are displayed automatically when the user enters the field. By using jQuery with Ajax, we can easily present automated proposals for all queries from the database in the text field. I don't use the jQuery plugin to ask for text fields for autocomplete

This Three steps to implement autocomplete Search

  1. Create a database connection
  2. Create an autocomplete search form
  3. Create PHP code for search from database

 

1. Create a database connection

We first need to create a database connection to extract the city name from the database.

Page Name - config.php

 

<?php    
$host = "localhost"; /* Host name */    
$user = "root"; /* User */    
$password = "root"; /* Password */    
$dbname = "study"; /* Database name */    
$con = mysqli_connect($host, $user, $password,$dbname);    
// Check connection    
if (!$con) {    
die("Connection failed: " . mysqli_connect_error());    
}    
?>    

 

2. Create an autocomplete search form

Now create the HTML search form page for searching the city name and autocomplete

Page Name - Index.php


<!doctype html>  
<html>  
  <head>  
    <title>Make Autocomplete Search with jQuery AJAX</title>  
    <link href="style.css" rel="stylesheet" type="text/css">  
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <script src="jquery-3.3.1.js" type="text/javascript"></script>  
    <script type="text/javascript">  
      $(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);  
                });  
              }  
            });  
          }  
        });  
      });  
  
      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 link = response[0]['link'];  
              window.location = link;  
            }  
          }  
        });  
      }  
    </script>  
  </head>  
  <body>  
    <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>  
  </body>  
</html>  

 

 

3. Create PHP code for searching from the database

Page Name - search.php

<?php  
  
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 idservices,services_name,link FROM services where services_name LIKE '%$searchText%'";  
$result = mysqli_query($con,$sql);  
$search_arr = array();  
    while($fetch = mysqli_fetch_assoc($result)){  
        $idservices = $fetch['idservices'];  
        $services_name = $fetch['services_name'];  
        $link = $fetch['link'];  
        $search_arr[] = array("id" => $idservices, "name" => $services_name, "link" => $link);  
    }  
        echo json_encode($search_arr);  
}  
  
// get User data  
  
if($type == 2){  
      
    $userid = mysqli_real_escape_string($con,$_POST['userid']);  
      
    $sql = "SELECT link FROM services where idservices=".$userid;  
    $result = mysqli_query($con,$sql);  
    $return_arr = array();  
    while($fetch = mysqli_fetch_assoc($result)){  
        $link = $fetch['link'];  
        $return_arr[] = array("link"=>$link);  
    }  
        echo json_encode($return_arr);  
}  

 

 

For Styling

Page Name - Style.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;  
    }  

 

 

 

Sample image for clarification

For downloading the source code click on the link mentioned below

How to Create A auto-complete search with Jquery, AJAX, and PHP


Please Share this course

It Looks like you have completed your course!! We have created Online series based on the above content. You can give a test and check your skill.




Be a Part of CollegeSpike by giving your precious comment here and help us in improving our content.