Ajax autocomplete dropdown field with bootstrap 4 and jquery in PHP

I have seen in many posts, a lot of plugins with many many lines to make  a autocomplete field. I think is much more simple.

Let’s make it !

What you need ? only 3 pieces.

  1. HTML based on boostrap.
  2. Jquery to make a ajax call to get autocomplete data.
  3. PHP to give to jquery results to autocomplete

Before you need to include jquery and bootstrap to your html page  :

  • jquery-2.2.4.min.js
  • bootstrap.min.js
  • bootstrap.min.css

1. HTML based on boostrap.

</pre>
<div class="form-group">Country:
<div class="dropdown">
<div id="result" class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdownMenuLink"></div>
</div>
</div>
<pre>

2. Jquery to make a ajax call to get autocomplete data.

The javascript jquery code is :


$(document).ready(function() {

  $("#fieldname").keyup(function() {
       var name = $('#fieldname').val();
       if (name == "") {
          $("#result").hide();
       } else {
          $.ajax({
               type: "POST",
               url: "ajax.php",
               data: {
               search: name
               }, success: function(html) {
                    $('#result').html(html).show();
                    $("#result a").click(function() {
                      fill($(this).attr('href'),$(this).text());
                    });
               }});
        }
    });
});

function fill(href, Value) {
     $('#fieldname').val(Value);
     $('#result').hide();
}

“fill” function is no needed, is just to make it more structured. We pass also href, but also is not needed.

3. PHP to give to jquery results to autocomplete

That script will search in your database for data that contains the string being written.

I’m just going to show you where the php script returns the values ​​to the “ajax” call.

If you have 3 results of the search : text1, text2, text3

For every result you would have an echo as follow :

// getting the string written by user
$search = $_POST["search"];

//making search in your database
...
// end database search

foreach ($query_result as $item){
echo '<a class="dropdown-item" role="option" href="#">'.$item["text"].'</a>';
}

That’s all !!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s