Tuesday, 25 September 2018

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

Database Tables

  1. CREATE TABLE `continents` (
  2. `continent_id` int(11) NOT NULL AUTO_INCREMENT,
  3. `continent` varchar(255) NOT NULL,
  4. PRIMARY KEY(`continent_id`)
  5. )
  6. CREATE TABLE `countries` (
  7. `country_id` int(11) NOT NULL AUTO_INCREMENT,
  8. `country` varchar(255) NOT NULL,
  9. `continent_id` int(11) NOT NULL COMMENT 'continent_id from the continents table',
  10. PRIMARY KEY(`country_id`)
  11. )
  12. CREATE TABLE `states` (
  13. `state_id` int(11) NOT NULL AUTO_INCREMENT,
  14. `state` varchar(255) CHARACTER SET latin1 NOT NULL,
  15. `country_id` int(11) NOT NULL COMMENT 'country_id from the countries table',
  16. PRIMARY KEY(`state_id`)
  17. )
  18. CREATE TABLE `cities` (
  19. `city_id` int(11) NOT NULL AUTO_INCREMENT,
  20. `city` varchar(255) NOT NULL,
  21. `state_id` int(11) NOT NULL COMMENT 'state_id from the states table',
  22. PRIMARY KEY(`city_id`)
  23. )
Download the complete source code for sample data for the above tables.

Database Connection (db.php)

  1. <?php
  2. define('HOSTNAME','localhost');
  3. define('DB_USERNAME','DATABASE_USERNAME');
  4. define('DB_PASSWORD','DATABASE_PASSWORD');
  5. define('DB_NAME', 'DATABASE_NAME');
  6. $con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
  7. // Check connection
  8. if(mysqli_connect_errno($con)) echo "Failed to connect MySQL: " .mysqli_connect_error();
  9. ?>
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)

  1. <?php include('db.php'); ?>
  2. <div class="container-fluid">
  3. <div class="row">
  4. <div class="col-xs-12 col-md-sm-6 col-md-3">
  5. <label>Continent :</label>
  6. <select name="continent" class="form-control" id="continent">
  7. <option value=''>------- Select --------</option>
  8. <?php
  9. $sql = "select * from `continents`";
  10. $res = mysqli_query($con, $sql);
  11. if(mysqli_num_rows($res) > 0) {
  12. while($row = mysqli_fetch_object($res)) {
  13. echo "<option value='".$row->continent_id."'>".$row->continent."</option>";
  14. }
  15. }
  16. ?>
  17. </select>
  18. </div>
  19. <div class="col-xs-12 col-md-sm-6 col-md-3">
  20. <label>Country :</label>
  21. <select name="country" class="form-control" id="country" disabled="disabled"><option>------- Select --------</option></select>
  22. </div>
  23. <div class="col-xs-12 col-md-sm-6 col-md-3">
  24. <label>State / Province / County :</label>
  25. <select name="state" class="form-control" id="state" disabled="disabled"><option>------- Select --------</option></select>
  26. </div>
  27. <div class="col-xs-12 col-md-sm-6 col-md-3">
  28. <label>City / Popular Place :</label>
  29. <select name="city" class="form-control" id="city" disabled="disabled"><option>------- Select --------</option></select>
  30. </div>
  31. </div>
  32. </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)

  1. $(document).ready(function() {
  2. //Change in continent dropdown list will trigger this function and
  3. //generate dropdown options for county dropdown
  4. $(document).on('change','#continent', function() {
  5. var continent_id = $(this).val();
  6. if(continent_id != "") {
  7. $.ajax({
  8. url:"get_data.php",
  9. type:'POST',
  10. data:{continent_id:continent_id},
  11. success:function(response) {
  12. //var resp = $.trim(response);
  13. if(response != '') {
  14. $("#country").removeAttr('disabled','disabled').html(response);
  15. $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  16. } else {
  17. $("#country, #state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  18. }
  19. }
  20. });
  21. } else {
  22. $("#country, #state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  23. }
  24. });
  25. //Change in coutry dropdown list will trigger this function and
  26. //generate dropdown options for state dropdown
  27. $(document).on('change','#country', function() {
  28. var country_id = $(this).val();
  29. if(country_id != "") {
  30. $.ajax({
  31. url:"get_data.php",
  32. type:'POST',
  33. data:{country_id:country_id},
  34. success:function(response) {
  35. //var resp = $.trim(response);
  36. if(response != '') {
  37. $("#state").removeAttr('disabled','disabled').html(response);
  38. $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  39. }
  40. else $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  41. }
  42. });
  43. } else {
  44. $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  45. }
  46. });
  47. //Change in state dropdown list will trigger this function and
  48. //generate dropdown options for city dropdown
  49. $(document).on('change','#state', function() {
  50. var state_id = $(this).val();
  51. if(state_id != "") {
  52. $.ajax({
  53. url:"get_data.php",
  54. type:'POST',
  55. data:{state_id:state_id},
  56. success:function(response) {
  57. if(response != '') $("#city").removeAttr('disabled','disabled').html(response);
  58. else $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  59. }
  60. });
  61. } else {
  62. $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  63. }
  64. });
  65. });
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)

  1. <?php include('db.php');?>
  2. <?php
  3. if (isset($_POST['continent_id'])) {
  4. $qry = "select * from countries_new where continent_id=".mysqli_real_escape_string($con,$_POST['continent_id'])." order by country";
  5. $res = mysqli_query($con, $qry);
  6. if(mysqli_num_rows($res) > 0) {
  7. echo '<option value="">------- Select -------</option>';
  8. while($row = mysqli_fetch_object($res)) {
  9. echo '<option value="'.$row->country_id.'">'.$row->country.'</option>';
  10. }
  11. } else {
  12. echo '<option value="">No Record</option>';
  13. }
  14. } else if(isset($_POST['country_id'])) {
  15. $qry = "select * from states_new where country_id=".mysqli_real_escape_string($con,$_POST['country_id'])." order by state";
  16. $res = mysqli_query($con, $qry);
  17. if(mysqli_num_rows($res) > 0) {
  18. echo '<option value="">------- Select -------</option>';
  19. while($row = mysqli_fetch_object($res)) {
  20. echo '<option value="'.$row->state_id.'">'.$row->state.'</option>';
  21. }
  22. } else {
  23. echo '<option value="">No Record</option>';
  24. }
  25. } else if(isset($_POST['state_id'])) {
  26. $qry = "select * from cities where state_id=".mysqli_real_escape_string($con,$_POST['state_id'])." order by city";
  27. $res = mysqli_query($con, $qry);
  28. if(mysqli_num_rows($res) > 0) {
  29. echo '<option value="">------- Select -------</option>';
  30. while($row = mysqli_fetch_object($res)) {
  31. echo '<option value="'.$row->city_id.'">'.$row->city.'</option>';
  32. }
  33. } else {
  34. echo '<option value="">No Record</option>';
  35. }
  36. }
  37. ?>
Based on the continent_idcoutry_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.

0 comments:

Post a Comment