Creating search box suggestions with Ajax

Creating search box suggestions with Ajax is pretty simple

There are some steps to be followed:

  1. Creating a form where the user inputs and search options are displayed.
  2. AJAX function to make asynchronous call to database to display matching results (ajax).
  3. PHP script to process and compute results.

Creating search box suggestions with Ajax

Here is demo database:
Creating search box suggestions with Ajax

What it would look like:
Creating search box suggestions with Ajax

Creating the form

This form will contain a simple input where the user will enter the values.For demo we are searching among cities in India.

<form method="get" action="#">
<label>I'm looking for:</label>
<input list="cities" id="input_city_window" class='input_city_window' placeholder="Enter your city" required="required" onkeyup="suggest_city()"/>
<datalist id="cities">
<!-- we will leave this empty as output will be displayed by php -->

Passing entered value to PHP script -Ajax jQuery function

This function will work on key-up.

function suggest_city()
   var val=$("#input_city_window").val();
   var dataTosend='city='+val;
                url: 'check-city.php',
                type: 'POST',
        async: true,
        success: function (data) {
  • val() is jQuery function to get input value. dataTosend holds the data that is to be sent to PHP script. The data is sent in form of name value pair where “city” is the name and variable “val” holds the value.
  • To understand the ajax function refer to Passing data to php script using Ajax. Here the “data” holds the data that is sent, which in this case is held in dataTosend variable. Call is made to “check-city.php”.
  • success function is used to display the response generated by script.
    $("datalist").append(data); would add the various values returned to datalist element.

Creating the php script

This script will do the processing on the database to find values that match the string entered.


// establishing a database connection
  define("HOST", "localhost");     // The host you want to connect to.
  define("USER", "user_db");    // The database username. 
  define("PASSWORD", "123$%bb^7aqq!2");    // The database password. 
  define("DATABASE", "sample_db");    // The database name.
  $connection = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
  // Check connection
  if (mysqli_connect_errno())
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
  //getting value in variable $searchTerm


  //query to search
   $sql="SELECT * FROM `cities` WHERE `citynames` LIKE '%".$searchTerm."%' ";
  //running query
   $result= mysqli_query($connection,$sql);

    while ($row=mysqli_fetch_assoc($result)) {  
         echo "<option value='{$row['city_name']}'>{$row['city_name']}</option>";

  • $searchTerm=$_POST['city']; is used to get the value passed by ajax to script using the name value pair, here “city”is the name used to pass the value.
  • SELECT * FROM `cities` WHERE `citynames` LIKE '%".$searchTerm."%' matches the columns having value matching the string held in $searchTerm using SQL LIKE operator.
  • Whatever is echo by this script is directly passed to the success function of Ajax as data.
    Now the success function can be used to display this data on our html page. {$row['city_name']} contains the value fetched.Here we are using option tag because we will display the result in the datalist element.

Leave a Reply

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