Integrate Auto Complete Search To Your Web Application

In this tutorial, we will integrate an auto-suggest feature to our existing web application. We will implement facebook’s user-search functionality in this tutorial.

Auto Suggest feature helps to generate recommendations based on letters you type in the text box thus reducing user effort and enhance user experience.

Like Google uses auto suggest for their search queries and Facebook to search People,Events,Places etc.

We will be using PHP as server-sided language for this tutorial , since, it is easy club with Typehead.js library.

(Note : I have used XAMMP Server to run PHP Scripts )

Let’s dive into it.

We will need a basic web page which consist of a text-field which accepts input from the user.

We will implement the auto-suggest feature on that text-field using typehead.js through ajax call.


Basic Web Page

In our web page , we have used :-

  • Bootstrap 3
  • JQuery library
  • Typehead.js library

To Setup Bootrstrap:-

Use a Bootstrap CDN from here & add it to <head> section of your web page.

To Setup JQuery :-

Use a Jquery CDN from here & add it to <body> section of your web page.

To Setup Typehead.js:-

Use Typehead CDN from here & add it to <body> section of your webpage.


Our basic web page will look like :-

<!DOCTYPE html>
<html lang="en">
   <head>
      <!-- BOOTSTRAP LIBRARY -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
      <title>Basic Web Page</title>
   </head>
   <body>
      <!--JQUERY & TYPEHEAD.JS -->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
   
<!-- ADD YOUR CODE HERE -->





<!-- ENDS HERE -->

</body>
</html>

Now, we will add a text-field to our web page , we are using predefined bootstrap classes to style our web page.

<!--NAV BAR -->
      <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
         <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Our Search</a>
         </div>
         <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <div class="col-sm-3 col-md-3 col-md-offset-1 ">
               <form class="navbar-form" role="search" action="#" method="GET">
                  <div class="input-group">
                     <input type="text" class=" form-control" placeholder="Search" name="q" id="users">
                     <div class="input-group-btn">
                        <button class="btn btn-success" type="submit"><i class="glyphicon glyphicon-search"></i></button>
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </nav>
<!-- NAV BAR ENDS HERE-->

In the above code, we have added a top navigation bar to our web page with a search text-field in it & a button.

Our web page is complete , now we will add auto suggest functionality to our search-field.


Type Head Ajax Call – Auto Suggest Feature

<script>
$(document).ready(function(){
  $('#users').typeahead({
    source: function(query, result){
      $.ajax({
        url:"Suggest.php",
        method:"POST",
        data:{query:query},
        dataType:"json",
        success:function(data){
          result($.map(data, function(item){
            return item;
          }));
        }
      });
    }
  });  
});
</script>

Add the above code in our <body> section of the web-page.

What does the above code do?.

At line no 2, whenever a web-page body is loaded, .ready() function gets called.

At line no 3, (“#users”) is actually a ID of the search-field in our web page. we are calling .typehead() function on text-field.

At line no 5, we are actually doing a ajax call with following parameters:-

  • URL – Destination file name to reach after call
  • METHOD – POST/GET for call.
  • DATA – input or query passed by the text-field.
  • DATA_TYPE – type of data to return after successful call.

At line no 10, After a successful call to the destination file , we are specifying to return the item.


The PHP File – Server Sided Scripting

Now, we have to write the code to handle what should be done after a call reaches the destination file.

Add the following code to your PHP file :-

<?php
$connect = mysqli_connect("localhost", "root", "", "scattr");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query   = "
 SELECT * FROM scattr_users WHERE FirstName LIKE '%" . $request . "%'";
$result = mysqli_query($connect, $query);
$data = array();
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = "  " . $row["FirstName"] . " " . $row['LastName'];
    }
    echo json_encode($data);
}
?>

At line now 1 , we are connecting to the mysql data base with the proper credentials.

At line No 4, SQL statement which returns the first name if sub-strings is matched.

At line No 6 , we executed the SQL query.

At line No 12, we are finally encoding the data into JSON & returning to the user.

Thats all, our auto-suggest feature has been integrated in our web application.

Final Output :-

We are searching user’s by typing their names & auto-suggestions are displayed.

If you find the above article helpful, please share it.

Any Suggestions to improve the article are highly recommended in comment section.

Happy Coding!.

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create your website at WordPress.com
Get started
%d bloggers like this: