How to Create a jQuery Ajax and PHP Autocomplete Script

jquery logo.png

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.

countryAutocomplete.png

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:

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.

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 straightforward but please feel free to ask questions if you are unsure.

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.

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.

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.

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

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.

STEP 4: Create the getCountry.php file

The final step in this creation process!

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