Populate multiple dropdown lists using Ajax, jQuery, PHP and MySQL

  •  
  •  
  •  
  •  
  •  
  •  

Some readers often asking me how to generate or populate more than one dropdown list or multiple select boxes using Ajax. So, In this tutorial, I will show you how to generate or populate multiple dropdown lists using Ajax, jQuery, PHP, and MySQL.

Let’s think a situation where the user has to submit a form where he/she has to fill up the form by selecting continent, country, state, and city. Country list is dependent on the selection of continent, state list is dependent on the selection of the country list and so on. All this dynamically generated select or dropdown options are using Ajax so that no page refresh or reload is required.

If you want to populate only one dropdown list based on selection of another dropdown option, please read this article — populate a dropdown list based on selection of another dropdown option using ajax

Populate multiple dropdown lists using Ajax, jQuery, PHP and MySQL

Database Tables

CREATE TABLE `continents` (
  `continent_id` int(11) NOT NULL AUTO_INCREMENT,
  `continent` varchar(255) NOT NULL,
  PRIMARY KEY(`continent_id`)
) 

CREATE TABLE `countries` (
  `country_id` int(11) NOT NULL AUTO_INCREMENT,
  `country` varchar(255) NOT NULL,
  `continent_id` int(11) NOT NULL COMMENT 'continent_id from the continents table',
  PRIMARY KEY(`country_id`)
)

CREATE TABLE `states` (
  `state_id` int(11) NOT NULL AUTO_INCREMENT,
  `state` varchar(255) CHARACTER SET latin1 NOT NULL,
  `country_id` int(11) NOT NULL COMMENT 'country_id from the countries table',
  PRIMARY KEY(`state_id`)
) 

CREATE TABLE `cities` (
  `city_id` int(11) NOT NULL AUTO_INCREMENT,
  `city` varchar(255) NOT NULL,
  `state_id` int(11) NOT NULL COMMENT 'state_id from the states table',
   PRIMARY KEY(`city_id`)
)

Download the complete source code for sample data for the above tables.

Database Connection (db.php)

<?php
define('HOSTNAME','localhost');
define('DB_USERNAME','DATABASE_USERNAME');
define('DB_PASSWORD','DATABASE_PASSWORD');
define('DB_NAME', 'DATABASE_NAME');

$con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
// Check connection
if(mysqli_connect_errno($con))	echo "Failed to connect MySQL: " .mysqli_connect_error();
?>

The above PHP code is responsible for establishing the database connection with MySQL. Change the database name, username, and password with your credentials.

HTML – Populate Multiple Dropdown Lists (index.php)

<?php include('db.php'); ?>

<div class="container-fluid">
  <div class="row">

    <div class="col-xs-12 col-md-sm-6 col-md-3">
      <label>Continent :</label>
      <select name="continent" class="form-control" id="continent">
        <option value=''>------- Select --------</option>
        <?php 
        $sql = "select * from `continents`";
        $res = mysqli_query($con, $sql);
        if(mysqli_num_rows($res) > 0) {
          while($row = mysqli_fetch_object($res)) {
            echo "<option value='".$row->continent_id."'>".$row->continent."</option>";
          }
        }
        ?>
      </select>
    </div>

    <div class="col-xs-12 col-md-sm-6 col-md-3">
      <label>Country :</label>
      <select name="country" class="form-control" id="country" disabled="disabled"><option>------- Select --------</option></select>
    </div>


    <div class="col-xs-12 col-md-sm-6 col-md-3">
      <label>State / Province / County :</label>
      <select name="state" class="form-control" id="state" disabled="disabled"><option>------- Select --------</option></select>
    </div>


    <div class="col-xs-12 col-md-sm-6 col-md-3">
      <label>City / Popular Place :</label>
      <select name="city" class="form-control" id="city" disabled="disabled"><option>------- Select --------</option></select>
    </div>
  </div>
</div>

Only for the continent dropdown list the list of continents will be generated through the PHP code on page load or page refresh.

Ajax – Populate Multiple Dropdown Lists using Ajax (mtb.js)

$(document).ready(function() {

  //Change in continent dropdown list will trigger this function and
  //generate dropdown options for county dropdown
  $(document).on('change','#continent', function() {
    var continent_id = $(this).val();
    if(continent_id != "") {
      $.ajax({
        url:"get_data.php",
        type:'POST',
        data:{continent_id:continent_id},
        success:function(response) {
          //var resp = $.trim(response);
          if(response != '') {
            $("#country").removeAttr('disabled','disabled').html(response);
            $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
          } else {
            $("#country, #state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
          }
        }
      });
    } else {
      $("#country, #state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
    }
  });


  //Change in coutry dropdown list will trigger this function and
  //generate dropdown options for state dropdown
  $(document).on('change','#country', function() {
    var country_id = $(this).val();
    if(country_id != "") {
      $.ajax({
        url:"get_data.php",
        type:'POST',
        data:{country_id:country_id},
        success:function(response) {
          //var resp = $.trim(response);
          if(response != '') {
            $("#state").removeAttr('disabled','disabled').html(response);
            $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
          }
          else $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
        }
      });
    } else {
      $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
    }
  });



  //Change in state dropdown list will trigger this function and
  //generate dropdown options for city dropdown
  $(document).on('change','#state', function() {
    var state_id = $(this).val();
    if(state_id != "") {
      $.ajax({
        url:"get_data.php",
        type:'POST',
        data:{state_id:state_id},
        success:function(response) {
          if(response != '') $("#city").removeAttr('disabled','disabled').html(response);
          else $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
        }
      });
    } else {
      $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
    }
  });
});

The above jQuery and Ajax code are responsible for generating or populating the multiple dropdown lists.

PHP – Fetch Data From MySQL Database (get_data.php)

<?php include('db.php');?>

<?php

if (isset($_POST['continent_id'])) {
  
  $qry = "select * from countries_new where continent_id=".mysqli_real_escape_string($con,$_POST['continent_id'])." order by country";
  $res = mysqli_query($con, $qry);
  if(mysqli_num_rows($res) > 0) {
    echo '<option value="">------- Select -------</option>';
    while($row = mysqli_fetch_object($res)) {
      echo '<option value="'.$row->country_id.'">'.$row->country.'</option>';
    }
  } else {
    echo '<option value="">No Record</option>';
  }

} else if(isset($_POST['country_id'])) {

  $qry = "select * from states_new where country_id=".mysqli_real_escape_string($con,$_POST['country_id'])." order by state";
  $res = mysqli_query($con, $qry);
  if(mysqli_num_rows($res) > 0) {
    echo '<option value="">------- Select -------</option>';
    while($row = mysqli_fetch_object($res)) {
      echo '<option value="'.$row->state_id.'">'.$row->state.'</option>';
    }
  } else {
    echo '<option value="">No Record</option>';
  }

} else if(isset($_POST['state_id'])) {

  $qry = "select * from cities where state_id=".mysqli_real_escape_string($con,$_POST['state_id'])." order by city";
  $res = mysqli_query($con, $qry);
  if(mysqli_num_rows($res) > 0) {
    echo '<option value="">------- Select -------</option>';
    while($row = mysqli_fetch_object($res)) {
      echo '<option value="'.$row->city_id.'">'.$row->city.'</option>';
    }
  } else {
    echo '<option value="">No Record</option>';
  }
}

?>

Based on the continent_id, coutry_id and state_id, data will fetch from the database respectively.

Complete Source Code – Populate Multiple Dropdown Lists Using Ajax

Download the complete source code from the below Download link. Also, you can try the live demo on Populate Multiple Dropdown Lists Using from the below Demo link. Please like and share this tutorial with others.

About Mitrajit

10 comments on “Populate multiple dropdown lists using Ajax, jQuery, PHP and MySQL

  1. Greetings, I am contacting you using your contact form but the recapture is preventing me.

    Greetings.
    I am developing an SMS application in php to send messages to phone numbers stored in a database.
    I want to use php exception handling to model this so that, it can show number of sent messages, Received and those did not go, I click on resend to send it again.

  2. Sir
    First of all very much interactive code, Thank a lot for this. Sir i want to Display Data in table from database based on last dropdown(city) selection Using Ajax in above example. Kindly help me out.

  3. thanks, for the good work in fact i have been searching the web for 4 dynamic dropdown for months now but you brought relieve with this explanation.
    I have a little challenge in re-editing the code for use especially the jquery where you use continent, country state and city.
    i tried to change it to oldgroup, group, district and address following exactly your instruction but it doesnt work. kindly help.

  4. Awesome tutorial Mitrajit, extremely easy to follow and very well written 🙂 I’m using a variation of this code and have added some more JQuery functions to fit my needs, but I learned a lot from you, thanks very much!

Leave a Reply

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

Prove you are a human *