Autocomplete textbox using jQuery, PHP and MySQL

By | May 22, 2016

Autocomplete is a very useful project for user’s. It gives a list of things what you are searching according to your entered text. It saves time and offer’s a list of products and services with same names. It will give user’s more ideas based on their searching.

I have a list of states in India in my SQL file you can download it from bottom so we will use the same database and try the autocomplete search.

In this tutorial you will see how we use the PHP, Jquery,Mysql for populate the list of words and phrases based on your keyword entered. In this tutorial you will see how we will use search the database using matching records entered by the user.

In this example we will use 2 files. index.php and autocomplete-search.php and some CSS for styling our list. Lets start with our index.php

Index.php

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <input type="text" class="form-control input-lg" id="statelist" name="statelist" placeholder="Search State Name" value="">
        <br/>
        <div id="suggesstion-box">         
        </div>
    </body>
</html>

We have created a simple form which is having a textbox and a suggestion box. Suggestion box is for list based on our searched keyword.

Autocomplete-Search.php

<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_USER_NOTICE);
$host="localhost";$dbname="datacopier";$dbpass="";$dbuser="root";$con;
$con=mysqli_connect($host, $dbuser, $dbpass, $dbname);
if(!empty($_POST["keyword"])) {
    $query ="SELECT State_name FROM webstate WHERE State_name like '" . $_POST["keyword"] . "%' ORDER BY State_name LIMIT 0,8";
    $result = mysqli_query($con, $query);
    $count=  mysqli_num_rows($result);
        if($count < 1){
            echo "Not found your state";
        }
else
{
    $alert='<ul id="state-list">';
    while($row=  mysqli_fetch_array($result)){
        $name=$row["State_name"];
        $alert.="<li onClick='selectState(\"$name\")'>$name</li>";
    }
    $alert.="</ul>";
    echo $alert;
}
} ?>

First you have to setup the database variables.  Now just import the downloaded SQL file into your database. You will get a table named webstate. If your keyword variable is not empty than it will run the sql query. If SQL query returns any result than our while loop will create a list of State Name’s.

Jquery Part

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
	$("#statelist").keyup(function(){
		$.ajax({
		type: "POST",
		url: "autocomplete-search.php",
		data:'keyword='+$(this).val(),
		success: function(data){
			$("#suggesstion-box").show();
			$("#suggesstion-box").html(data);
		}
		});
	});
});
function selectState(val) {
$("#statelist").val(val);
$("#suggesstion-box").hide();
}
    </script>

We are using keyup function for getting the list. When you enters any character than  ajax function will send the post request to autocomplete-search.php page with variable named “keyword”.

Keyword is having the value which you enter into the box.  When your query returns any value than it will popup the list.

selectState function is used to enter the list value in textbox. After clicking the list value our list will hide and value will be entered into the textbox.

Hope you like our tutorial if you find any issue or want to ask anything related to tutorial than please comment below.

Autocomplete Textbox (2.4 KiB, 590 downloads)

4 thoughts on “Autocomplete textbox using jQuery, PHP and MySQL

  1. Ravindra

    how to give alert if other than suggested value is entered or typed in textbox. Thanks in advance for any help…

    Reply
    1. Vivek Moyal Post author

      I am not sure but if you can try this it will work for you.
      replace this
      if($count < 1){ echo "Not found your state"; }
      to this
      if($count < 1){ echo "1"; }
      and under jquery part
      replace this
      success: function(data){
      $("#suggesstion-box").show();
      $("#suggesstion-box").html(data);
      }

      to this
      success: function(data){
      if(data=="1"){alert("This is a trial";)}else{
      $("#suggesstion-box").show();
      $("#suggesstion-box").html(data);}
      }

      Reply
      1. Ravindra

        Thanks a lot…. but it does not show suggestion list for entered alphabet it gives alert for every time I press button.
        I want to check if user changes that suggested value after selection if yes then give alert for “Selecet only from suggested list”

        Reply
        1. Ravindra

          Sorry for above comment. I tried it and its working, there was error in my “seacrh.php” file once its corrected its working…..thanks again

          Reply

Leave a Reply

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