Ajax dropdown list from Database using PHP and jQuery

Dropdown is the best way to force user to select any one option by giving him/her a list of options. But sometimes there is a dependency to select next option which is based on previous option.

Just like, if you are in a shopping cart website trying to purchase any product. First you must select a country then website automatically populates a list of cities based on your selection.

This whole process from country to cities is based on AJAX. First shopping cart website shows country in a dropdown from database and when user select any country then cities are populated under countries dropdown.

So in this tutorial we are going to cover this process.


Ajax dropdown list from database using PHP and jQuery

Let’s note down what we are going to do.

  • Create database as demo.
  • Create 2 tables in the demo database. One table is for country and second is for cities.
  • Create a config.php file and create database connection using mysqli_connect() function.
  • Create index.php file which include config.php file, write css, html, php and jquery ajax code.
  • Create ajax_request.php which will get country id and populate cities based on given country id.

ajax country cities dropdown

Create Database:

Create Country Table:

Insert records in Country Table:

Create Cities Table:

Insert records in Cities Table:

Create Database Connection File: (config.php)

HTML: (index.php)

In the above code. First I get all the countries and show them in dropdown by using while loop. You might also notice that I used ajax-loader.gif image that have loader id. By default loader will hide. It will only appear when country will change. Then there is cities-container div. I will show cities under cities-container div.

ajax country dropdown

CSS: (style.css)

jQuery Ajax Request: (index.php)

Get Ajax Request And Send Data: (ajax_request.php)

Also read:

 

Leave a Reply

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