问题描述:

i have made chained select boxes i.e each select box is dependent on another select box except first select box.

when page loads user select country then state select box get populated and after state selection city select box get populated.

The chained select boxes is working fine.

PROBLEM

When Page loads it has few results,on each selection result should also get filtered

EG:

1. when page loads mix results get displayed

2.on country selection on results related to this country should be displayed

3 after state selection results related to that country and state should get displayed.

this is the part where i'm stuck.someone helps me out

My code is

HTML AND 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>');

}

});

});

SERVER SIDE CODE

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: **Should i use multiple ajax calls

EDIT: i solved it using multiple ajax call

HTML And 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";

}

}

网友答案:

No need multiple ajax request instead of single one.

$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);
         }
      });
}

Also combine dependent and result file into one.

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 : '') );
}
?>
相关阅读:
Top