简体   繁体   中英

cascading dropdown menu with sql ajax

I have database with 5 tables. Each table is a subcatagory of the previous one, called:

  • countries
  • states
  • cities
  • ZIPcode
  • streets

Now I have 3 dropdowns which depend on each other. So when I select countries: USA , the next dropdown wil only show USA-states etc. This works.

But now I want to extend to 5 dropdowns, so adding 2 more.

I don't show what I've tried to add 2 more, because it will probably only make it more complex.

So I show the 3 dropdowns that are working now:

file: ajax.php

<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');

if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $db->query("SELECT * FROM states WHERE country_id =    ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");

//Count total number of rows
$rowCount = $query->num_rows;

//Display states list
if($rowCount > 0){
    echo '<option value="">Select state</option>';
    while($row = $query->fetch_assoc()){ 
        echo '<option      value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
    }
}else{
    echo '<option value="">State not available</option>';
}
}

if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM cities WHERE state_id =  ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");

//Count total number of rows
$rowCount = $query->num_rows;

//Display cities list
if($rowCount > 0){
    echo '<option value="">Select city</option>';
    while($row = $query->fetch_assoc()){ 
        echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
    }
}else{
    echo '<option value="">City not available</option>';
}
}
?>

****The index.php-file**** (I didn't add the css):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
    var countryID = $(this).val();
    if(countryID){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'country_id='+countryID,
            success:function(html){
                $('#state').html(html);
                $('#city').html('<option value="">Select state first</option>'); 
            }
        }); 
    }else{
        $('#state').html('<option value="">Select country first</option>');
        $('#city').html('<option value="">Select state first</option>'); 
    }
});

$('#state').on('change',function(){
    var stateID = $(this).val();
    if(stateID){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'state_id='+stateID,
            success:function(html){
                $('#city').html(html);
            }
        }); 
    }else{
        $('#city').html('<option value="">Select state first</option>'); 
    }
});
});
</script>
</head>
<body>
<div class="select-boxes">
<?php
//Include database configuration file
include('dbConfig.php');

//Get all country data
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");

//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="country" id="country">
    <option value="">Select Country</option>
    <?php
    if($rowCount > 0){
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
        }
    }else{
        echo '<option value="">Country not available</option>';
    }
    ?>
</select>

<select name="state" id="state">
    <option value="">Select country first</option>
</select>

<select name="city" id="city">
    <option value="">Select state first</option>
</select>
</div>
</body>
</html>

See, I modified your code a little bit.

I don't have any idea about your street & zipcode table column name or dropdown. I assumed and did. Change it wherever needed in dropdow or in query. It will help you. Go through it.

And, if any doubt, feel free to ask.

index.php

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>

  </head>
  <body>
    <div class="select-boxes">
      <?php include('dbConfig.php'); //Include database configuration file ?>
      <div class="country">
        <?php
        $query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
        $rowCount = $query->num_rows;
        ?>
        <select name="country" id="country">
          <option value="">Select Country</option>
          <?php
          if ($rowCount > 0) {
            while ($row = $query->fetch_assoc()) {
              echo '<option value="' . $row['country_id'] . '">' . $row['country_name'] . '</option>';
            }
          } else {
            echo '<option value="">Country not available</option>';
          }
          ?>
        </select>
      </div>

      <div class="showStateCity">
        <select name="state" id="state">
          <option value="">Select country first</option>
        </select>
        <select name="city" id="city">
          <option value="">Select state first</option>
        </select>

        <select name="zipcode" id="zipcode">
          <option value="">Select City first</option>
        </select>

        <select name="streets" id="streets">
          <option value="">Select Zipcode first</option>
        </select>

      </div>

    </div>
  </body>
</html>
<script src="jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
    $('#country').on('change',function(){
      getStateCityZipCodeStreets();
    });

    $('#state').on('change',function(){
      getStateCityZipCodeStreets();
    });

    $('#city').on('change',function(){
      getStateCityZipCodeStreets();
    });

    $('#zipcode').on('change',function(){
      getStateCityZipCodeStreets();
    });

    function getStateCityZipCodeStreets(){
      var country = $('#country').val();
      var state = $('#state').val();
      var city = $('#city').val();
      var zipcode = $('#zipcode').val();

      $.ajax({
          type:'POST',
          url:'ajaxData.php',
          data:{country_id:country, state_id :state, city_id : city, zipcode_id : zipcode},
          cache:false,
          success:function(data){
            $('.showStateCity').html(data);
          }
      }); 
    }
  });
</script>

ajaxData.php

<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');

/*States*/
$queryState = "SELECT * FROM states WHERE 1=2";
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
  $queryState = "SELECT * FROM states WHERE status = 1 AND country_id =".$_POST['country_id']." ORDER BY state_name ASC";
}
$execQueryState = $db->query($queryState);
$rowCountState = $execQueryState->num_rows;

/*City*/
$queryCity = "SELECT * FROM cities WHERE 1=2";
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
  $queryCity = "SELECT * FROM cities WHERE status = 1 AND state_id".$_POST['state_id']." ORDER BY city_name ASC";
}
$execQueryCity = $db->query($queryCity);
$rowCountCity = $execQueryCity->num_rows;

/*ZipCode*/
$queryZipcode = "SELECT * FROM zipcode WHERE 1=2";
if(isset($_POST["city_id"]) && !empty($_POST["city_id"])){
  $queryZipcode = "SELECT * FROM zipcode WHERE status = 1 AND city_id".$_POST['city_id']." ORDER BY zipcode ASC";
}
$execQueryZipCode = $db->query($queryZipcode);
$rowCountZipCode = $execQueryZipCode->num_rows;

/*Streets*/
$queryStreets = "SELECT * FROM streets WHERE 1=2";
if(isset($_POST["zipcode_id"]) && !empty($_POST["zipcode_id"])){
  $queryStreets = "SELECT * FROM streets WHERE status = 1 AND zipcode_id".$_POST['zipcode_id']." ORDER BY street_name ASC";
}
$execQueryStreets = $db->query($queryStreets);
$rowCountStreets = $execQueryStreets->num_rows;
?>

<select name="state" id="state">
  <option value="">Select country first</option>
  <?php
  if($rowCountState > 0){
    while($rowState = $execQueryState->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowState['state_id'];?>"><?php echo $rowState['state_name'];?></option>
  <?php }
  } else {?>
  <option value="">State Not Available</option>
  <?php }?>
</select>

<select name="city" id="city">
  <option value="">Select state first</option>
  <?php
  if($rowCountCity > 0){
    while($rowCity = $execQueryCity->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowCity['city_id'];?>"><?php echo $rowCity['city_name'];?></option>
  <?php }
  } else {?>
  <option value="">City Not Available</option>
  <?php }?>
</select>

<select name="zipcode" id="zipcode">
  <option value="">Select City first</option>
  <?php
  if($rowCountZipCode > 0){
    while($rowZipCode = $execQueryZipCode->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowZipCode['zipcode_id'];?>"><?php echo $rowZipCode['zipcode'];?></option>
  <?php }
  } else {?>
  <option value="">ZipCode Not Available</option>
  <?php }?>
</select>

<select name="streets" id="streets">
  <option value="">Select ZipCode first</option>
  <?php
  if($rowCountStreets > 0){
    while($rowStreets = $execQueryStreets->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowStreets['street_id'];?>"><?php echo $rowStreets['street_name'];?></option>
  <?php }
  } else {?>
  <option value="">Streets Not Available</option>
  <?php }?>
</select>

You need to create a two more table zipcode and streets and add a city_id in zipcode table and zip_id in streets table

 <select name="zipcode" id="zipcode">
     <option value="">Select Zipcode first</option>
 </select>

 <select name="streets" id="streets">
      <option value="">Select Streets first</option>
 </select>

Jquery Scrtipt

$('#city').on('change',function(){
    var cityId = $(this).val();
    if(cityId){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'city_id='+cityId,
            success:function(html){
                $('#zipcode').html(html);
            }
        }); 
    }else{
        $('#zipcode').html('<option value="">Select zipcode first</option>'); 
    }
});
});

$('#zipcode').on('change',function(){
    var zipId = $(this).val();
    if(zipId){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'zip_id='+zipId,
            success:function(html){
                $('#streets').html(html);
            }
        }); 
    }else{
        $('#streets').html('<option value="">Select Streets first</option>'); 
    }
});
});

Php code is same as state just need to change table name and fields

By using this you get the cascading dropdown menu of zipcode and streets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM