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)


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

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


 0) {
    echo "";
    while($row = mysqli_fetch_object($res)) {
      echo "";
    }
  }
} 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.

Leave a Comment