How to Dynamic Populate Values in One HTML Dropdown List With Another Using Simple Javascript PHP?

Today, We want to share with you dynamic populating the drop down list based on the selected value of first list.In this post we will show you show a second dropdown based on previous dropdown selection in php, hear for Populate a dropdown list based on selection of another dropdown list using ajax we will give you demo and example for implement.In this post, we will learn about javascript dropdown onchange another dropdown with an example.

How to Auto populate dropdown with jQuery AJAX?

AngularJS populate Dynamic Dependent dropdown List using PHP MySQLi
Step 1: 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');

Step 2: Database Connection (db.php)

<?php
define('HOSTNAME','localhost');
define('DB_USERNAME','username');
define('DB_PASSWORD','password');
define('DB_NAME', 'shop_v1');
//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();
?>

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

$(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>");
    }
  });
});

Example 4: 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: ./');
}
?>

I hope you get an idea about php dynamic drop down list onchange.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.