简体   繁体   English

使用SQL Ajax的级联下拉菜单

[英]cascading dropdown menu with sql ajax

I have database with 5 tables. 我有5表的数据库。 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. 现在我有3个下拉列表,它们相互依赖。 So when I select countries: USA , the next dropdown wil only show USA-states etc. This works. 因此,当我选择countries: USA ,下一个下拉列表将仅显示USA-states等。

But now I want to extend to 5 dropdowns, so adding 2 more. 但是现在我想扩展到5个下拉菜单,所以再添加2个。

I don't show what I've tried to add 2 more, because it will probably only make it more complex. 我没有展示我尝试增加2个的内容,因为它可能只会使其变得更复杂。

So I show the 3 dropdowns that are working now: 因此,我显示了现在可以使用的3个下拉列表:

file: ajax.php 档案: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. 我对您的streetzipcode表的列名或下拉列表一无所知。 I assumed and did. 我假设并做到了。 Change it wherever needed in dropdow or in query. 在dropdow或查询中根据需要进行更改。 It will help you. 它会帮助你。 Go through it. 经过它。

And, if any doubt, feel free to ask. 并且,如有任何疑问,请随时提出。

index.php 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 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 您需要再创建两个表邮政编码和街道,并在邮政编码表中添加city_id,在街道表中添加zip_id

 <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 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 PHP代码与状态相同,只需要更改表名和字段

By using this you get the cascading dropdown menu of zipcode and streets. 通过使用此选项,您可以获得邮政编码和街道的级联下拉菜单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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