Populate a dropdown list based on selection of another dropdown list using ajax

  •  
  •  
  •  
  •  
  •  
  •  

This tutorial will you help to populate a dropdown list based on selection of another dropdown option using ajax. What actually we do here, let’s assume we have two dropdown list in a form. The first dropdown list is the list of countries where users can select one country. The second dropdown list will display only the states it belongs to the selected country dynamically through ajax means no page refreshing.

Also, you can enjoy the live demo example on Populate a dropdown list based on selection of another dropdown list using ajax for better understanding. As well as you can get the full source code from the download link.

If you want to generate or populate multiple dropdown lists using Ajax then click on the following article — Populate multiple dropdown lists using Ajax, jQuery, PHP, and MySQL.

Populate a dropdown list based on selection of another dropdown list using ajax

Database Tables

CREATE TABLE `countries` (
  `id` int(11) NOT NULL,
  `country` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


CREATE TABLE `states` (
  `id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL COMMENT 'id of the countries table',
  `state` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


INSERT INTO `countries` (`id`, `country`) VALUES
(1, 'India'),
(2, 'America');


INSERT INTO `states` (`id`, `country_id`, `state`) VALUES
(2, 1, 'West Bengal'),
(3, 1, 'Maharastra'),
(4, 1, 'Goa'),
(5, 1, 'Kerala'),
(6, 2, 'Newyork'),
(7, 2, 'Ohio'),
(8, 2, 'Texas');

For dynamically populate or generate the dropdown list using ajax, you need two tables in the database. The above queries will create two tables and insert some data into these two tables respectively.

Database Connection (db.php)

<?php
define('HOSTNAME','localhost');
define('DB_USERNAME','username');
define('DB_PASSWORD','password');
define('DB_NAME', 'database-name');

//global $con;
$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();
?>

Establishing a database connection using PHP is an important part of this example. Replace usernamepassword, and database-name with your credentials.

HTML – Dynamically Populate Dropdown List Using Ajax (index.php)

Let’s follow the below code which lets you help to dynamically generate the dropdown list using ajax.

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<?php include("db.php");?>
<div class="">
    <label>Country :</label>
    <select name="country" id="country">
      <option value=''>------- Select --------</option>
      <?php 
      $sql = "select * from `countries`";
      $res = mysqli_query($con, $sql);
      if(mysqli_num_rows($res) > 0) {
        while($row = mysqli_fetch_object($res)) {
          echo "<option value='".$row->id."'>".$row->country."</option>";
        }
      }
      ?>
    </select>
    
    <label>State :</label>
    <select name="state" id="state"><option>------- Select --------</option></select>
  </div>

As you can see above, we created two dropdown list. The first dropdown list is for the country list which is dynamic and it comes from the database during the page load by using a simple PHP code. The second dropdown list will dynamically generate the list of states based on the selection of the country dropdown list using Ajax and PHP.

Ajax Call – Create Dynamic dropdown (ajax.js)

$(document).ready(function() {
  $("#country").change(function() {
    var country_id = $(this).val();
    if(country_id != "") {
      $.ajax({
        url:"get-states.php",
        data:{c_id:country_id},
        type:'POST',
        success:function(response) {
          var resp = $.trim(response);
          $("#state").html(resp);
        }
      });
    } else {
      $("#state").html("<option value=''>------- Select --------</option>");
    }
  });
});

When you first select or change any country from the first dropdown list the $(“#country”).change(function() {….}) will come into action. Variable country_id holds the id of the selected country. If it is not null then $.ajax({….}) will send an Ajax post request to the get-states.php page with the country id.

Fetch The List Of The States (get-states.php)

<?php include("db.php"); ?>
<?php
if(isset($_POST['c_id'])) {
  $sql = "select * from `states` where `country_id`=".mysqli_real_escape_string($con, $_POST['c_id']);
  $res = mysqli_query($con, $sql);
  if(mysqli_num_rows($res) > 0) {
    echo "<option value=''>------- Select --------</option>";
    while($row = mysqli_fetch_object($res)) {
      echo "<option value='".$row->id."'>".$row->state."</option>";
    }
  }
} else {
  header('location: ./');
}
?>

The above code is a simple PHP code which returns the list of states based on the country id from the database. mysqli_real_escape_string() function escapes special characters from a string. It is very useful to prevent SQL injection.

Complete Source Code – Populate a dropdown list based on selection of another dropdown list using ajax

Try the live demo example on Populate a dropdown list based on selection of another dropdown list using ajax. Download the complete source code from the below download link and please like and share the tutorial link with others.

About Mitrajit

24 comments on “Populate a dropdown list based on selection of another dropdown list using ajax

    1. Hi Rozanna,
      I don’t know why the second drop down is not working at your site. Whatever I upload the full working script, you can download it from here.

      1. I’m really sorry it was just a small mistake from my side its working perfectly and thanks a lot to you.

    1. Hi Daniel,
      data:{c_id:country_id}, ‘country_id’ is a variable which stores the id of the country. When we pass values over a network through GET or POST method, we need to bind these values to named variables. So, here ‘c_id’ the variable which passing over the network carrying the id of the country. You can download the script from the download link at the bottom which consists the database schema.

    1. Hi Chan,
      In the source code I included “jquery.min.js”, but it was not present in the folder which you downloaded. So, please keep a “jquery.min.js” in the project root folder or download the new version of the source code from the same link.

  1. THE STATE DROPDOWN IS NOT BEING POPULATED. IN QUERY TEXT IN ALTER TABLE YOU MENTIONED CID WHILE THERE IS NO FIELD IN THE TABLE AS CID. I CHANGED THE FIELD NAME AS COUNTRY_ID, EVEN IT DOES NOT WORK

    1. You are right D P Jindal, it should be “country_id” not “CID”. But whatever the alter query does not affect the sole purpose of this program. In the source code I included “jquery.min.js”, but it was not present in the folder which you downloaded. So, please keep a “jquery.min.js” in the project root folder or download the new version of the source code from the same link. Sorry for late reply.

      1. In the source code I included “jquery.min.js”, but it was not present in the folder which you downloaded. So, please keep a “jquery.min.js” in the project root folder or download the new version of the source code from the same link. Sorry for late reply.

      2. Respected Sir…..Is it possible to developed such kind of dropdown list using only mysql and jsp and jscript….

  2. Dear Mr. Mitrajit,
    I have develop a program like yours, but in my case I use JSON to generate the second dropdown list. And it works without problem.

    What I am trying to do is that when a user click SUBMIT button and when the form validation is fails (I use codeigniter form validation), I want the second dropdown list is remain selected (which is actually generated dynamically from the first dropdown like yours).

    What is happening now is that the select portion is returning to the first option again (the “please select” option part, not the selected one before I click SUBMIT).

    Is there a way to do this (the second dynamically dropdown list is remain selected)?

    I hope my question is clear enough.

    Thank you

  3. Hi Mitrajit,

    I managed to create a dynamic second dropdown menu following your example. It is working as expected, which is great..!!

    However, I would like to provide the same set of dropdowns (dd) more than once in the same form (The dropdowns are not about country and cities, but something else).
    Is that possible?
    What modification need to be done to the ajax function so that I can use it multiple times. The results generated from the set of dd1 and dd2 will be inserted in table

  4. Hello Sir I Am Getting Empty Option in select tool when loading dynamically along with what i need
    Can You Tell Me where i could have went wrong.

  5. Works very well – and the “bigger version” with more levels is good too.

    BUT I am having what I think is a silly difficulty and I cant see why.

    Having selected the ‘state’ i want to pass it on for additional processing.
    Preferably as a Session variable but I just cant seem to get the usual POST to work either – am I missing something.

    Just for completeness I would also add a simple numerical quantity in and also pass it on
    say
    State – Kerala
    Count – 6

    Somehow I am missing something very simple I think – could I ask your insight??

Leave a Reply

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

Prove you are a human *