How to Create a jQuery Ajax and PHP Autocomplete Script

In this lesson we will create an autocomplete script using jQuery and PHP. Autocomplete fields can be extremely useful for searching through database records and making suggestions to the user.

For this example we will create a simple input field in which we will start to enter a country name. Using AJAX we will then search a database and return the suggestions to the user as a list under the input field.

The image below gives an indication of what we will be creating. We can see the input field (currently showing br) and the suggested countries below.

Country Autocomplete

We will require the following files:

  • style.css (some basic styling for the input field and suggestions)
  • index.php (this file will contain the jQuery, input field and suggestions) 
  • getCountry.php (take the input from the input field, search the database and return the result to index.php)

In addition, you will need to create a database table in which to store the list of countries.

STEP 1: Create the database table

The table will require at least one field, which will be the country. It is up to you if you wish to include additional fields such as the 2-letter country code.

You will find various CSV and SQL dumps of country names by doing a quick search on the web. Otherwise, feel free to download the attached SQL dump.

STEP 2: Create the index.php file

We will start with a very simple HTML5 template as follows:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Autocomplete Script</title>
   </head>
   <body>      
   </body>
</html>

Since we will be using jQuery for the AJAX call we will need to include a link to a jQuery script (line 6). I tend to use Google's CDN for jQuery.

We will also need to add a link to the style.css file (line 7). Although we have not yet created the stylesheet we might as well include the link now.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Autocomplete Script</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <link rel="stylesheet" href="style.css">     
   </head>
   <body>
   </body>
</html>

We can now start to work on the input field and area to hold the suggestions. 

Lines 11 to 14 show the structure of the input area. Hopefully this is all fairly striaghtforward but please feel free to ask questions if you are unsure.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Autocomplete Script</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <link rel="stylesheet" href="style.css">
   </head>
   <body>
      
      <div class="countrySearch">
         <input type="text" id="country" placeholder="Country">
         <div id="suggestions"></div>
      </div>
      
   </body>
</html>

We can now start to work on the jQuery code. 

We want the code to run once the page has loaded. We therefore use a ready function which is shown in lines 10-12 below. This simply means that we want any code in-between lines 10 and 12 to run once the page has fully loaded and the document is ready.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Autocomplete Script</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <link rel="stylesheet" href="style.css">
      <script>
         
         $(function(){
            
         });
         
      </script>
   </head>
   <body>
      
      <div class="countrySearch">
         <input type="text" id="country" placeholder="Country">
         <div id="suggestions"></div>
      </div>
      
   </body>
</html>

When a user types something in the input field we need to check the database for suggestions.

We therefore reference the #country id and run a function when a keyup has been detected.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Autocomplete Script</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <link rel="stylesheet" href="style.css">
      <script>
         
         $(function(){
            $("#country").keyup(function(){
               
            });
         });
           
      </script>
   </head>
   <body>
      
      <div class="countrySearch">
         <input type="text" id="country" placeholder="Country">
         <div id="suggestions"></div>
      </div>
      
   </body>
</html>

The next thing we need to do is to get the contents of whatever has been entered into the #country field.

Line 12: we have declared a variable called countryName which will hold the value of $(this). Using $(this) is a quick way of referencing the #country field identified on line 11.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Autocomplete Script</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <link rel="stylesheet" href="style.css">
      <script>
         
         $(function(){
            $("#country").keyup(function(){
               var countryName = $(this).val();
               
            });
         });
         
      </script>
   </head>
   <body>
      
      <div class="countrySearch">
         <input type="text" id="country" placeholder="Country">
         <div id="suggestions"></div>
      </div>
      
   </body>
</html>

We now need to write the code to handle the AJAX call (lines 12 to 20):

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Autocomplete Script</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <link rel="stylesheet" href="style.css">
      <script>

         $(function(){
            $("#country").keyup(function(){
               var countryName = $(this).val();
               $.ajax({
                  method: "POST",
                  url: "getCountry.php",
                  data:{country:countryName}
               })
                  .done(function(data){
                  $("#suggestions").show();
                  $("#suggestions").html(data);
               });
            });
         });

      </script>
   </head>
   <body>

      <div class="countrySearch">
         <input type="text" id="country" placeholder="Country">
         <div id="suggestions"></div>
      </div>

   </body>
</html>

Line 13: we declare the start of the AJAX call

Line 14: we will be using a POST method (like the POST method used when handling HTML forms)

Line 15: we declare the URL where we will be posting our data. This will be the script that will search the database for whatever country name we pass to it.

Line 16: we declare the data we will be posting to the getCountry.php script as a key:value pair. In this case we will be posting a country which has the value represented by countryName (the variable we declared earlier)

Lines 18 - 20: once the data has been sent and we have a response we then process the returned data. We first show the #suggestions div and then update the html content to show the returned data.

STEP 3: Create the style.css file

Hopefully you will find this css fairly self-explanatory. Again, if you have any questions please feel free to post them below.

body, input {
   font-family: Arial, Helvetica, sans-serif;
   font-size: 12px;
}

.countrySearch {
   width: 300px;
   padding: 40px;
   background: #baebe1;
}

#countries {
   list-style-type: none;
   margin: 0;
   padding: 0;
   width: 200px;
}

#countries li {
   padding: 10px; 
   background: #FFF;
   border-bottom: #F0F0F0 1px solid;
}

#countries li:hover {
   background:#F0F0F0;
   cursor: pointer;
   cursor: hand;
}

#country {
   padding: 10px;
}

STEP 4: Create the getCountry.php file

The final step in this creation process!

<?php
require_once("yourDatabaseConnectionScript.php");
if(!empty($_POST['country'])) {
   $query ="SELECT * FROM countries WHERE country LIKE '" . $_POST['country'] . "%' ORDER BY country";
   $result = $db->query($query);
   if(!empty($result)) {
      echo "<ul id='countries'>";
      foreach($result as $country) {
         echo "<li>" . $country['country'] . "</li>";
      }
      echo "</ul>";
   } 
}

Line 2: you will need to add your own database credentials or a link to your database connection script.

I used a PDO connection and had the credentials stored in a separate file.

Some of this code will need to be amended depending on your connection type.

Line 3: here we check if there is any data. If the posted country value is not empty then continue with the rest of the script.

NOTE: I have not taken into account any security for this script. Since this is just a basic introduction I did not wish to start adding more code. However, you MUST ensure your own scripts are secure before placing them on a live environment.

Line 4: the SQL statement. We are checking if there are any matches in the database which are LIKE the posted data. Note the use of the % wildcard. This means that if we entered uni into the search then all records with the first 3 letters uni and ANYTHING after that would be returned.

Line 5: we execute the query. Again, I would highly recommend using prepared statements.

Line 6: we check if there are any returned results from the database query

Line 7: we start to form the list of countries by creating an unordered list with a class of 'countries' 

Line 8: we start to loop through the results

Line 9: this line creates a HTML list item containing the name of the country.

Line 11: we close the unordered list

Want to Learn More?

Become a member and get access to the member only area of this site here.

Comments

Your email address will not be published.

User Avatar

Many thanks for this excellent tutorial. Very well explained. I would like to know what security measures I need to take (you mentioned this in your note)

by Freddie, 05-Jan-2016

User Avatar

@Freddie the security measurements you need to take will ultimately depend on what you are going to be doing with the user data. For example, if entering into a database then consider something like the filter_var function as a minimum.

by Patrick Morrow, 05-Jan-2016

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.