Dependent Drop-down List in PHP MYSQL using jQuery AJAX

 This tutorial is very much helpful in creating multi-level dependent drop down list by using PHP MYSQL. 

The following is the example for choosing Location based on it's Sub-district, District & State as shown below.


Step 1:

First create  index.php file with the following code.

<?php
// Include the database connection file
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "";
 $db = "dbname";
 $con = mysqli_connect($dbhost, $dbuser, $dbpass , $db) or die($con);
?>
 
<html>
<head>
 <title>Multi level Dependent Select Box using jQuery, Ajax and PHP MYSQL - Lonarbi</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
 <div class="container">
 <h3>Dynamic Dependent Select Box></h3>
    <br />
 <form action="" method="post">
 <div class="col-md-4">
 
 <!-- State dropdown -->
 <label for="state">State</label>
 <select class="form-control" id="state">
 <option value="">Select State</option>
 <?php
 $query = "SELECT DISTINCT state FROM search_location";
 $result = $con->query($query);
 if ($result->num_rows > 0) {
 while ($row = $result->fetch_assoc()) {
 echo '<option value="'.$row['state'].'">'.$row['state'].'</option>';
 }
 }else{
 echo '<option value="">State not available</option>';
 }
 ?>
 </select>
        <br />
 
 <!-- District dropdown -->
 <label for="district">District</label>
 <select class="form-control" id="district">
 <option value="">Select State</option>
 </select>
        <br />
 
 <!-- Sub District dropdown -->
 <label for="subDistrict">Sub District</label>
 <select class="form-control" id="subDistrict">
 <option value="">Select Sub Dist</option>
 </select>
        <br />
 
 <!-- Location dropdown -->
 <label for="location">Location</label>
 <select class="form-control" id="location">
 <option value="">Select Location</option>
 </select>

 </div>
 </form>
 </div>

 <script type="text/javascript">
  $(document).ready(function(){
    // Country dependent ajax
    $("#state").on("change",function(){
      var stateName = $(this).val();
      $.ajax({
        url :"action.php",
        type:"POST",
        cache:false,
        data:{state_name:stateName},
        success:function(data){
          $("#district").html(data);
          $('#subDistrict').html('<option value="">Select Sub District</option>');
        }
      });
    });
 
    // District dependent ajax
    $("#district").on("change", function(){
      var distName = $(this).val();
      $.ajax({
        url :"action.php",
        type:"POST",
        cache:false,
        data:{dist_name:distName},
        success:function(data){
          $("#subDistrict").html(data);
          $('#location').html('<option value="">Select Location</option>');
        }
      });
    });

    // Location dependent ajax
    $("#subDistrict").on("change", function(){
      var subDistName = $(this).val();
      $.ajax({
        url :"action.php",
        type:"POST",
        cache:false,
        data:{sub_dist_name:subDistName},
        success:function(data){
          $("#location").html(data);
        }
      });
    });
  });
</script>
</body>
</html>

 

Step 2:

Create  a mysql table with fields like state, district, subDist, location and insert some relevant data

 

Step 3:

Create  action.php file in the same directory with the following code for Database activity.

<?php
    
    // include database connection file

    $dbHost     = "localhost";
  $dbUsername = "root";
  $dbPassword = "";
  $dbName     = "dbname";
   
  // Create database connection
  $con = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
   
  // Check connection
  if ($con->connect_error) {
      die("Connection failed: " . $con->connect_error);
  }
    // autocomplete textbox jquery ajax in PHP
    
    if (isset($_POST['state_name']) && !empty($_POST['state_name'])) {
 
         // Fetch state name base on country id
         $query = "SELECT DISTINCT district FROM search_location WHERE state = '".$_POST['state_name']."'";
         $result = $con->query($query);
         
         if ($result->num_rows > 0) {
         echo '<option value="">Select District</option>';
         while ($row = $result->fetch_assoc()) {
         echo '<option value="'.$row['district'].'">'.$row['district'].'</option>';
         }
         } else {
         echo '<option value="">District not available</option>';
         }
    } elseif(isset($_POST['dist_name']) && !empty($_POST['dist_name'])) {
 
         // Fetch District name base on state id
         $query = "SELECT DISTINCT subDist FROM search_location WHERE district = '".$_POST['dist_name']."'";
         $result = $con->query($query);
         
         if ($result->num_rows > 0) {
         echo '<option value="">Select Sub Dist</option>';
         while ($row = $result->fetch_assoc()) {
         echo '<option value="'.$row['subDist'].'">'.$row['subDist'].'</option>';
         }
         } else {
         echo '<option value="">Sub District not available</option>';
         }   

    } elseif(isset($_POST['sub_dist_name']) && !empty($_POST['sub_dist_name'])) {
 
         // Fetch District name base on state id
         $query = "SELECT DISTINCT location FROM search_location WHERE subDist = '".$_POST['sub_dist_name']."'";
         $result = $con->query($query);
         
         if ($result->num_rows > 0) {
         echo '<option value="">Select Location</option>';
         while ($row = $result->fetch_assoc()) {

             if (strpos($row['location'], ',') !== false) {
                 $myLocation = explode(', ', $row['location']);
            
                 for ($i=0; $i < count($myLocation); $i++) {
                     echo '<option value="'.$myLocation[$i].'">'.$myLocation[$i].'</option>';
                 }                
             }
             else {
                     echo '<option value="'.$row['location'].'">'.$row['location'].'</option>';
             }         
         }
         } else {
         echo '<option value="">Location not available</option>';
         }
    }
?>

Every thing is done!!!

Previous
Next Post »
Related Posts Plugin for WordPress, Blogger...