Tuesday 7 June 2016

Ajax Autocomplete textbox using jQuery, PHP and MySQL

Ajax Autocomplete textbox is extremely user friendly for any Website. In this post you can get the knowledge regarding how to develop a same like google search textbox in PHP. By using jQuery  with Ajax we can smoothly present auto suggestion of any query from the database under textbox. Here I have not use any jquery query plugin for Autocomplete textbox but I have used simple Ajax method with PHP and Mysql for Autocomplete textbox. Now Let us start the autocomplete textbox tutorial. Here we will present a textbox for country entry. When user starting to type country name, it will display the country name started by character which he was enter into textbox and country would be listed under the textbox. These type of auto sugges country will be selected from the mysql database country table.


Database


 CREATE TABLE IF NOT EXISTS `tbl_country` (  
  `country_id` int(11) NOT NULL AUTO_INCREMENT,  
  `country_name` text NOT NULL,  
  PRIMARY KEY (`country_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=251 ;  
 --  
 -- Dumping data for table `tbl_country`  
 --  
 INSERT INTO `tbl_country` (`country_id`, `country_name`) VALUES  
 (1, 'Andorra'),  
 (2, 'United Arab Emirates'),  
 (3, 'Afghanistan'),  
 (4, 'Antigua and Barbuda'),  
 (5, 'Anguilla'),  
 (6, 'Albania'),  
 (7, 'Armenia'),  
 (8, 'Angola'),  
 (9, 'Antarctica'),  
 (10, 'Argentina'),  
 (11, 'American Samoa')  

auto_complete.php


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Autocomplete textbox using jQuery, PHP and MySQL</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <style>  
           ul{  
                background-color:#eee;  
                cursor:pointer;  
           }  
           li{  
                padding:12px;  
           }  
           </style>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:500px;">  
                <h3 align="center">Autocomplete textbox using jQuery, PHP and MySQL</h3><br />  
                <label>Enter Country Name</label>  
                <input type="text" name="country" id="country" class="form-control" placeholder="Enter Country Name" />  
                <div id="countryList"></div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#country').keyup(function(){  
           var query = $(this).val();  
           if(query != '')  
           {  
                $.ajax({  
                     url:"search.php",  
                     method:"POST",  
                     data:{query:query},  
                     success:function(data)  
                     {  
                          $('#countryList').fadeIn();  
                          $('#countryList').html(data);  
                     }  
                });  
           }  
      });  
      $(document).on('click', 'li', function(){  
           $('#country').val($(this).text());  
           $('#countryList').fadeOut();  
      });  
 });  
 </script>  

search.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 if(isset($_POST["query"]))  
 {  
      $output = '';  
      $query = "SELECT * FROM tbl_country WHERE country_name LIKE '%".$_POST["query"]."%'";  
      $result = mysqli_query($connect, $query);  
      $output = '<ul class="list-unstyled">';  
      if(mysqli_num_rows($result) > 0)  
      {  
           while($row = mysqli_fetch_array($result))  
           {  
                $output .= '<li>'.$row["country_name"].'</li>';  
           }  
      }  
      else  
      {  
           $output .= '<li>Country Not Found</li>';  
      }  
      $output .= '</ul>';  
      echo $output;  
 }  
 ?>  

22 comments:

  1. great was looking for something like this - when you backspace the inputfield to clear the results stay displayed - how the clear this ??

    i tried

    if (!empty ($ownersname)) {
    ...... rest of the script
    }else{
    $output = '';
    echo $output;
    }

    but its not working

    any feedback??

    ReplyDelete
    Replies
    1. Hi,

      Add in the script an ELSE condition with:

      $('#countryList').fadeOut();

      and ready!!!

      Delete
    2. Hi Bro,


      Add in the script an ELSE condition with:

      $('#countryList').fadeOut();

      and ready!!!

      Delete
  2. ON3PHP -----try this
    $( '#area' ).focusout(function() {
    $('#area').val($(this).text());
    $('#areaList').fadeOut();
    });

    ReplyDelete

  3. $(document).ready(function(){
    $('#country').keyup(function(){

    var name = $(this).val();

    if(name!='')
    {
    var site_url = $("#site_url").val();
    var url = site_url+"/Fade/countryAutocomplete";

    var datastring = "name="+name;


    $.ajax({
    url:url,
    type:'POST',
    data:datastring,
    success:function(data){

    $('#countryList').fadeIn();
    $('#countryList').html(data);
    }

    });
    }
    });
    $(document).on('click', 'li', function(){
    $('#country').val($(this).text());
    $('#countryList').fadeOut();
    });
    });

    ReplyDelete
  4. if (!empty ($ownersname)) {
    ...... rest of the script
    }else{
    $output = 'open---li no records found close---li';
    echo $output;
    }

    ReplyDelete
  5. how to input search results into the database ?

    ReplyDelete
  6. i've changed the search.php with sqlsrv query but it didn't work. is there anything i should add when changing the code?

    ReplyDelete
  7. sir how to add another css file in this code? i hoping for your reply. Thanks!

    ReplyDelete
  8. sir how to add another CSS file in this code? I'm hoping for the response. Thanks!

    ReplyDelete
  9. any feedback same problem of above unable to clear all.

    ReplyDelete
  10. https://jqueryui.com/autocomplete/#multiple-remote


    here availabe all types of autocomplete textbox

    ReplyDelete
  11. if having two fields they get filled by same value

    ReplyDelete
  12. you dont need to post an id ?

    ReplyDelete
  13. How do you add a second autocomplete textbox?

    ReplyDelete
  14. It doesnt work on my browser idunno why

    ReplyDelete
  15. it works, how to use keyboard up and down to select country?

    ReplyDelete