Back-End Development PHP and database

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.

Passing entered value to PHP script -Ajax jQuery function

This function will work on key-up.

  • 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.

  • $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.