在链接的选择框中过滤结果

时间:2016-08-01 06:55:16

标签: php jquery ajax

我已经制作了链式选择框,即每个选择框依赖于除第一个选择框之外的另一个选择框。 当页面加载用户选择国家,然后状态选择框被填充,并在状态选择城市选择框被填充后。 链式选择框工作正常 的问题 当页面加载时,它的结果很少,每个选择结果也应该被过滤 EG:
 1.当页面加载混合结果时显示
  2.应显示与该国家相关的结果的国家选择 3,状态选择结果与该国家和州相关应该显示。

这是我被困的部分。有人帮我出局 我的代码是
HTML和JQUERY

    <select name="country" id="country">
    <option>select country</option>
<?php
    $sql = "SELECT * from plus2_country ORDER BY country ASC";
    $result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
    $row_count = mysqli_num_rows($result);
    if($row_count > 0)
    {
        while($row = mysqli_fetch_array($result))
        {
             echo '<option value="'.$row['country_code'].'">'.$row['country'].'</option>';
        }
    }
    else
    {
        '<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>
<br>
<br>
<br>
<div id="results">
        <?php
            $query1 = "SELECT * from content ORDER BY emp_name";
            $result = mysqli_query($conn,$query1) or die(mysqli_error($conn));
            $row_count = mysqli_num_rows($result);
            if($row_count > 0)
            {
                while($row = mysqli_fetch_array($result))
                {
        ?>
                    <div class="col-md-3 photo-grid " style="float:left"> 

                        <div class="well well-sm">
                            <h4><small><?php echo $row['emp_name']; ?></small></h4>
                        </div>
                    </div>
        <?php
                }
            }
        ?>

<script type="text/javascript">
 $(document).ready(function(){

$('#country').on('change',function(){
    var country_code = $(this).val();
    console.log(country_code);
    if(country_code){
         $('#loadingmessage').show(); 
        $.ajax({
            type:'POST',
            url:'dependent.php',
            data:'country_code='+country_code,
            success:function(html){
                console.log(html);
                var $state_response = $(html);
                var $result_response = $(html);
                var state_option = $state_response.filter(".state_option").html();
                console.log(state_option);
                var results = $result_response.filter("#result").html();
                console.log(results);
                $('#state').html(html);
                $('#city').html('<option value="">Select state first</option>'); 
                $('#results').html(html);
                $('#loadingmessage').hide();
            }
        }); 
    }else{
        $('#state').html('<option value="">Select country first</option>');
        $('#city').html('<option value="">Select state first</option>'); 
    }
});
});  

服务器端代码

include 'dbconfig.php';
session_start();
if(isset($_POST["country_code"]) && !empty($_POST["country_code"])){
    $id = 1;
$code = $_POST['country_code'];
$code = mysqli_real_escape_string($conn,$code);
$query = "SELECT * FROM plus2_state WHERE country_code = '$code' ORDER BY state ASC";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
    while($row = mysqli_fetch_array($result)){ 
        echo '<option class="state_option" value="'.$row['state_id'].'">'.$row['state'].'</option>';        
    }
}else{
    echo '<option class="state_option" value="">State not available</option>';
}
$query_1 = "SELECT * from content where country_code = '$code' ORDER BY emp_name ASC";
$result_1 = mysqli_query($conn,$query_1) or die(mysqli_error($conn));
$row_count = mysqli_num_rows($result_1);
$_SESSION['result'] = array();
if($row_count > 0 )
{
    while($content_rows = mysqli_fetch_array($result_1))
    {
        unset($_SESSION['result']);
        echo "<div id='result'><div class='col-md-3 photo-grid' style = 'float:left'>
            <div class = 'well well-sm'><h4><small>".$content_rows['emp_name']."</small></h4></div></div></div>";
            $_SESSION['result'][$id] =  array('name' => $content_rows['emp_name']);
    }
}
else
{
    echo "<div class = 'result'>no results found</div>";
}
$_SESSION['country_code'] = $code ;
//print_r($_SESSION['result']);
}  

** PS:**我应该使用多个ajax调用

编辑:我使用多个ajax调用解决了它
HTML和Jquery

<select name="category" id="category">
    <option>select category</option>
<?php
    $sql = "SELECT * from category_ref_table ORDER BY category_name ASC";
    $result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
    $row_count = mysqli_num_rows($result);
    if($row_count > 0)
    {
        while($row = mysqli_fetch_array($result))
        {
             echo '<option value="'.$row['category_id'].'">'.$row['category_name'].'</option>';
        }
    }
    else
    {
        '<option value="">category not available</option>';
    }
?>
</select>
<select name="department" id="department">
    <option value="">Select category first</option>
</select>

<select name="course" id="course">
    <option value="">Select dept. first</option>
</select>
<select name="subject" id="subject">
    <option value="">Select course first</option>
</select>
<br>
<br>
<br>
<div class="results">
        <?php
            $query1 = "SELECT * from data_table ORDER BY title";
            $result = mysqli_query($conn,$query1) or die(mysqli_error($conn));
            $row_count = mysqli_num_rows($result);
            if($row_count > 0)
            {
                while($row = mysqli_fetch_array($result))
                {
        ?>
                    <div class="col-md-3 photo-grid " style="float:left"> 

                        <div class="well well-sm">
                            <h4><small><?php echo $row['title']; ?></small></h4>
                        </div>
                    </div>
              <?php
                }
            }
        ?>
      </div>
      <script type="text/javascript">
      $(document).ready(function(){
      $('#category').on('change',function(){
      var category_id = $(this).val();
      console.log(category_id);
      if(category_id){
        $.ajax({
            type:'POST',
            url:'dependent.php',
            data:'category_id='+category_id,
            success:function(html){
                console.log(html);
                console.log(category_id);
                $('#department').html(html);
                $('#course').html('<option value="">Select department first</option>'); 
               $.ajax({
                    type : 'POST',
                    url : 'results.php',
                    data : 'category_id='+category_id,
                    success : function(response)
                    {
                        console.log(response);
                        $('.results').html(response);
                    }
               });
            }
        }); 
    }else{
        $('#department').html('<option value="">Select category first</option>');
        $('#course').html('<option value="">Select department first</option>'); 
    }
});

$('#department').on('change',function(){
    var departmentID = $(this).val();
    console.log(departmentID);
    if(departmentID){
        $.ajax({
            type:'POST',
            url:'dependent.php',
            data:'dept_id='+departmentID,
            success:function(html){
                console.log(html);
                $('#course').html(html);
                $('#subject').html('<option value="">Select course first</option>');
                $.ajax({
                    type : 'POST',
                    url : 'results.php',
                    data : 'dept_id='+departmentID,
                    success : function(response)
                    {
                        console.log(response);
                        $('.results').html(response);
                    }
                });
            }
        }); 
    }else{
        $('#course').html('<option value="">Select department first</option>'); 
    }
});

$('#course').on('change',function(){
    var courseId = $(this).val();
    console.log(courseId);
    if(courseId)
    {
        $.ajax({
            type:'POST',
            url : 'dependent.php',
            data : 'course_id='+courseId,
            success : function(html){
                console.log(html);
                $('#subject').html(html)
                $.ajax({
                    type : 'POST',
                    url : 'results.php',
                    data : 'course_id='+courseId,
                    success : function(response)
                    {
                        $(".results").html(response);
                    }
                });
            }
        });
    }
    else{
        $('#subject').html('<option value="">Select Course first</option>'); 
    }
});
    $('#subject').on('change',function(){
    var subjectId = $(this).val();
    console.log(subjectId);
    if(subjectId)
    {
        $.ajax({
            type:'POST',
            url : 'results.php',
            data : 'subject_id='+subjectId,
            success : function(html){
                console.log(html);
                $('results').html(html);
            }
        });
    }
    else{
        $('#subject').html('<option value="">Select Course first</option>'); 
    }
   });
   });
  </script>  

dependent.php

<?php
include 'ajax_filters/dbconfig.php';
session_start();
if(isset($_POST["category_id"]) && !empty($_POST["category_id"])){
$code = $_POST['category_id'];
$query = "SELECT * FROM dept_ref_table WHERE category_id = '$code' ORDER BY dept_name ASC";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
    while($row = mysqli_fetch_array($result)){ 
        echo '<option value="'.$row['dept_id'].'">'.$row['dept_name'].'</option>';        
    }
  }else{
    echo '<option value="">Departments not available</option>';
   }
  }

if(isset($_POST["dept_id"]) && !empty($_POST["dept_id"])){
$dept_id = $_POST['dept_id'];
$code = $_SESSION['category_id'];
$query = "SELECT * FROM course_ref_table WHERE dept_id = '$dept_id'  ORDER BY course_name ASC";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
    echo '<option value="">Select Course</option>';
    while($row = mysqli_fetch_array($result)){ 
        echo '<option value="'.$row['course_id'].'">'.$row['course_name'].'</option>';
    }
}else{
    echo '<option value="">Courses not available</option>';
   }
  }
   if(isset($_POST['course_id']) && !empty($_POST['course_id']))
   {
   $course_id = $_POST['course_id'];
    $category_id = $_SESSION['category_id'];
   $dept_id = $_SESSION['dept_id'];
   $query = "SELECT * FROM subject_ref_table WHERE course_id = '$course_id'  ORDER BY subject_name ASC";
   $result = mysqli_query($conn,$query) or die(mysqli_error($conn));
   $rowCount = mysqli_num_rows($result);
   if($rowCount > 0){
    echo '<option value="">Select Subject</option>';
    while($row = mysqli_fetch_array($result)){ 
        echo '<option value="'.$row['subject_id'].'">'.$row['subject_name'].'</option>';
    }
 }else{
    echo '<option value="">subjects not available</option>';
 }
}
?>  

results.php

if(isset($_POST["category_id"]) && !empty($_POST["category_id"])){
    $id = 1;
    $category_id = $_POST['category_id'];
    $category_id = mysqli_real_escape_string($conn,$category_id);
    $sql = "SELECT * from data_table where category_id = '$category_id' order by title ASC ";
    $result = mysqli_query($conn,$sql) or mysqli_error($conn);
    $row_count = mysqli_num_rows($result);
    if($row_count > 0)
    {
        while($row = mysqli_fetch_array($result))
        {   
            //unset($_SESSION['result']);
            $_SESSION['result'][$id] =  array('title' => $row['title']);
            echo "<div id='result'><div class='col-md-3 photo-grid' style = 'float:left'>
                        <div class = 'well well-sm'><h4><small>".$row['title']."</small></h4></div></div></div>";
            $_SESSION['result'][$id] =  array('title' => $row['title']);
            $id++;
        }  
    $_SESSION['category_id'] = $category_id;
    print_r($_SESSION['result']);
    }
    else
    {
        echo "No results Found,we are still working on those keywords";
    }
}
    if(isset($_POST["dept_id"]) && !empty($_POST["dept_id"]))
    {
        $id = 1;
        $category_id = $_SESSION['category_id'];
        $dept_id = $_POST['dept_id'];
        $dept_id = mysqli_real_escape_string($conn,$dept_id);
        $sql = "SELECT * from data_table where category_id = '$category_id' and dept_id = '$dept_id' order by title ASC ";
        $result = mysqli_query($conn,$sql) or mysqli_error($conn);
        $row_count = mysqli_num_rows($result);
        if($row_count > 0)
        {
            while($row = mysqli_fetch_array($result))
            {
                echo "<div id='result'><div class='col-md-3 photo-grid' style = 'float:left'>
                            <div class = 'well well-sm'><h4><small>".$row['title']."</small></h4></div></div></div>";
                $_SESSION['result'][$id] = array('title' => $row['title']);

            }  
        $_SESSION['dept_id'] = $dept_id;
        print_r($_SESSION['result']);
        }
        else
        {
            echo "No results Found,we are still working on those keywords";
        }
    }
    if(isset($_POST["course_id"]) && !empty($_POST["course_id"]))
    {
        $id = 1;
        $category_id = $_SESSION['category_id'];
        $dept_id = $_SESSION['dept_id'];
        $course_id = $_POST['course_id'];
        $course_id = mysqli_real_escape_string($conn,$course_id);
        $sql = "SELECT * from data_table where category_id = '$category_id' and dept_id ='$dept_id' and course_id = '$course_id' order by title ASC ";
        $result = mysqli_query($conn,$sql) or mysqli_error($conn);
        $row_count = mysqli_num_rows($result);
        if($row_count > 0)
        {
            while($row = mysqli_fetch_array($result))
            {
                echo "<div id='result'><div class='col-md-3 photo-grid' style = 'float:left'>
                            <div class = 'well well-sm'><h4><small>".$row['title']."</small></h4></div></div></div>";
                $_SESSION['result'][$id] = array('title' => $row['title']);   
                $id++;      
            }  
        $_SESSION['course_id'] = $course_id;
        print_r($_SESSION['result']);
        }
        else
        {
            echo "No results Found,we are still working on those keywords";
        }
    }
    if(isset($_POST["subject_id"]) && !empty($_POST["subject_id"]))
    {
        $id = 1;
        $category_id = $_SESSION['category_id'];
        $dept_id = $_SESSION['dept_id'];
        $course_id = $_SESSION['course_id'];
        $subject_id = $_POST['subject_id'];
        $subject_id = mysqli_real_escape_string($conn,$subject_id);
        $sql = "SELECT * from data_table where category_id = '$category_id' and dept_id ='$dept_id' and course_id = '$course_id' and subject_id = '$subject_id' order by title ASC ";
        $result = mysqli_query($conn,$sql) or mysqli_error($conn);
        $row_count = mysqli_num_rows($result);
        if($row_count > 0)
        {
            while($row = mysqli_fetch_array($result))
            {
                echo "<div id='result'><div class='col-md-3 photo-grid' style = 'float:left'>
                            <div class = 'well well-sm'><h4><small>".$row['title']."</small></h4></div></div></div>";
                $_SESSION['result'][$id] = array('title' => $row[title]);
                $id++;   
            }  
        $_SESSION['course_id'] = $course_id;
        print_r($_SESSION['result']);
        }
        else
        {
            echo "No results Found,we are still working on those keywords";
        }
    }

1 个答案:

答案 0 :(得分:0)

不需要多个ajax请求而不是单个请求。

$depart = $('#department');
$course = $('#course');
$subj = $('#subject');

$res = $('.results');
$('#category,#department,#course,#subject').change(function(){
      c = 'category', d = 'department', o = 'course',
      ot = '<option value="">Select ', ct = ' first</option>';
      var s = 'subject', h = this, n = $(h).val(), k = h.id,
      el = (k==c) ? d : (k==d) ? o : s,
      jd =(k==c) ? {category_id:n} : (k==d) ? {dept_id:n} : 
      (k==o) ? {course_id:n} : {subject_id:n};
      console.log(k);
      if(k!=s){ dynoDropdowns(h, '#'+el, jd);
    } else {
        showres(h, jd);
    }
});

function seldt(e,d){
e.html(d);
}

function dynoDropdowns(el, nxtElem, dataObj){
var k = el.id, eo = ot+o+ct;
   if(k==c){ seldt($course, ot+d+ct); seldt($subj,eo);
    } else { seldt($subj,eo); }
    $.ajax({
        url:"op.php",
        type:"post",
        data:dataObj,
        dataType:"json",
        success:function(data){ console.log(data);
        $(nxtElem).empty()
                  .append('<option disabled>Select..</option>');
           $.each(data.ye, function(i, obj){
              $('<option>',
               { 
                   value:obj.s,
                   text:obj.d
               }
               ).appendTo(nxtElem);
           }); 
           eachres(data.pt);
        }
    });
}

function eachres(d){
$res.empty();
      $.each(d, function(i, ab){
          $('<div>',
          { 
            text:ab.nm
          }
          ).appendTo('.results');
      });
}
function showres(currElem, dataObj){
      $.ajax({
         url:"op.php",
         type:"post",
         data:dataObj,
         dataType:"json",
         success:function(data){ console.log(data);
            eachres(data.pt);
         }
      });
}

还将依赖和结果文件合并为一个。

op.php

<?php session_start();
include'ajax_filters/dbconfig.php';
$code = $_POST['category_id']; // (int) $_POST['category_id'];
$dept_id = $_POST['dept_id'];
$course_id = $_POST['course_id'];
$subject_id = $_POST['subject_id'];

$query = ($code) ? 'SELECT*FROM dept_ref_table WHERE category_id = '$code' ORDER BY dept_name ASC' :
         (($dept_id) ? 'SELECT*FROM course_ref_table WHERE dept_id = '$dept_id' ORDER BY course_name ASC' :
         'SELECT*FROM subject_ref_table WHERE course_id = '$course_id' ORDER BY subject_name ASC');
$vs = ($code) ? 'dept_id' : (($dept_id) ? 'course_id' : 'subject_id');
$ds = ($code) ? 'dept_name' : (($dept_id) ? 'course_name' : 'subject_name');

if(isset($query) && !empty($query)){
$result = mysqli_query($conn,$query) or die(mysqli_error($conn)); // need prepared statement
$h = mysqli_num_rows($result);

while($r = mysqli_fetch_array($result)){ // or fetch_num
$fil[] = ( array('s' => $r[$vs], 'd' => $r[$ds]) );
}

$qt = ($code) ? 'SELECT * from data_table where category_id = '$category_id' order by title ASC':
        (($dept_id) ? 'SELECT * from data_table where category_id = '$category_id' and dept_id = '$dept_id' order by title ASC':
        (($course_id) ? 'SELECT * from data_table where category_id = '$category_id' and dept_id ='$dept_id' and course_id = '$course_id' order by title ASC':
        'SELECT * from data_table where category_id = '$category_id' and dept_id ='$dept_id' and course_id = '$course_id' and subject_id = '$subject_id' order by title ASC'));
$result = mysqli_query($conn,$qt) or die(mysqli_error($conn)); // need prepared statement

while($r = mysqli_fetch_array($result)){
$jar[] = ( array('nm' => $r['title']) );
}
// json format.
echo json_encode( array('ye' => ($h>0) ? $fil : '',
                        'pt' => ($h>0) ? $jar : '') );
}
?>