multiple drop down list in php using ajax

Today, We want to share with you multiple drop down list in php using ajax.In this post we will show you dynamic drop down list in php using ajax, hear for how to select multiple options from a drop down list in php.

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

we will give you demo and example for implement.In this post, we will learn about Country State City Drop Down List Using JavaScript with an example.

Step 1: Database Tables

CREATE TABLE `universities` (
  `univercity_id` int(11) NOT NULL AUTO_INCREMENT,
  `univercity` varchar(255) NOT NULL,
  PRIMARY KEY(`univercity_id`)
) 
CREATE TABLE `departments` (
  `department_id` int(11) NOT NULL AUTO_INCREMENT,
  `department` varchar(255) NOT NULL,
  `univercity_id` int(11) NOT NULL COMMENT 'univercity_id from the universities table',
  PRIMARY KEY(`department_id`)
)
CREATE TABLE `branchs` (
  `branch_id` int(11) NOT NULL AUTO_INCREMENT,
  `branch` varchar(255) CHARACTER SET latin1 NOT NULL,
  `department_id` int(11) NOT NULL COMMENT 'department_id from the departments table',
  PRIMARY KEY(`branch_id`)
) 
CREATE TABLE `tasks` (
  `task_id` int(11) NOT NULL AUTO_INCREMENT,
  `task` varchar(255) NOT NULL,
  `branch_id` int(11) NOT NULL COMMENT 'branch_id from the branchs table',
   PRIMARY KEY(`task_id`)
)

Step 2: Database Connection (db.php)

<?php
define('HOSTNAME','localhost');
define('DB_USERNAME','YOUR_DB_USR_NAME');
define('DB_PASSWORD','DATABASE_PASSWORD');
define('DB_NAME', 'pakainfo_websites');
$con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
// Check DB connection
if(mysqli_connect_errno($con))  echo "Failed to connect MySQL: " .mysqli_connect_error();
?>

Step 3: 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>Univercity :</label>
      <select name="univercity" class="form-control" id="univercity">
        <option value=''>------- Select --------</option>
        <?php 
        $sql = "select * from `universities`";
        $res = mysqli_query($con, $sql);
        if(mysqli_num_rows($res) > 0) {
          while($row = mysqli_fetch_object($res)) {
            echo "<option value='".$row->univercity_id."'>".$row->univercity."</option>";
          }
        }
        ?>
      </select>
    </div>
    <div class="col-xs-12 col-md-sm-6 col-md-3">
      <label>Department :</label>
      <select name="department" class="form-control" id="department" disabled="disabled"><option>------- Select --------</option></select>
    </div>
    <div class="col-xs-12 col-md-sm-6 col-md-3">
      <label>Branch :</label>
      <select name="branch" class="form-control" id="branch" disabled="disabled"><option>------- Select --------</option></select>
    </div>
    <div class="col-xs-12 col-md-sm-6 col-md-3">
      <label>Task :</label>
      <select name="task" class="form-control" id="task" disabled="disabled"><option>------- Select --------</option></select>
    </div>
  </div>
</div>

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

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

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

<?php include('db.php');?>
<?php
if (isset($_POST['univercity_id'])) {
  
  $qry = "select * from departments_new where univercity_id=".mysqli_real_escape_string($con,$_POST['univercity_id'])." order by department";
  $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->department_id.'">'.$row->department.'</option>';
    }
  } else {
    echo '<option value="">No Record</option>';
  }
} else if(isset($_POST['department_id'])) {
  $qry = "select * from branchs_new where department_id=".mysqli_real_escape_string($con,$_POST['department_id'])." order by branch";
  $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->branch_id.'">'.$row->branch.'</option>';
    }
  } else {
    echo '<option value="">No Record</option>';
  }
} else if(isset($_POST['branch_id'])) {
  $qry = "select * from tasks where branch_id=".mysqli_real_escape_string($con,$_POST['branch_id'])." order by task";
  $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->task_id.'">'.$row->task.'</option>';
    }
  } else {
    echo '<option value="">No Record</option>';
  }
}
?>

I hope you get an idea about multiple drop down list in php using ajax.
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.

Read Also:  get multiple checkbox value in jquery

About Pakainfo

I am Jaydeep Gondaliya, a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Pakainfo →

Leave a Reply

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