Somename Somename - 4 months ago 7
MySQL Question

How to jquery ajax multiple selects

OK, my form is :

<form>

<select name="students" id="students">
<option value="0">Select Value First</option>
<option value="a">Value A</option>
<option value="b">Value B</option>
<option value="c">Value C</option>
</select>
<br /><br />
<select name="house" id="house">
<option value="0">Select Value Second</option>
<option value="a">Value A</option>
<option value="b">Value B</option>
<option value="c">Value C</option>
</select>
<br /><br />
<select name="location" id="location">
<option value="0">Select Value Third</option>
<option value="a">Value A</option>
<option value="b">Value B</option>
<option value="c">Value C</option>
</select>
<br /><br />

</form>


My jqeury is:

$(document).on("change","select",function() {
$val1 = $(this).val();
$val2 = $(this).attr('name');
$.get("selectdata.php",{"name":$val2,"id":$val1},function($data){
$("#result").html($data);
});
});


What i want to achieve is:
When the page loads, all students should be displayed. So my query is:
SELECT * FROM 'mytable' WHERE 'students'='students.val()' AND 'house'='house.val()' AND 'location'='location.val()';


When any option from select is selected, only that value should be changed in the SELECT statement. So for example, if anything from SELECT HOUSE is changed, the new SELECT statement will be:

SELECT * FROM 'mytable' WHERE 'students'='students.val()' AND 'house'='changedVALUE' AND 'location'='location.val()';


After this is anything from the SELECT LOCATION is changed, only the location value should be passed to the existing SELECT with condition for house selected in previous operation.

So basically i want the previous condition to be intact and pass the new condition on SELECT change.

I hope i am able to explain my issue. I am not sure how to create the jquery / php query.

Thanks.

Answer

Your jquery should be like this:

  $("#students, #house, #location").on("change", function(){
  var students = $("#students").val();
  var house = $("#house").val();  
  var location = $("#location").val();
  $.ajax({ 
    type: "POST", 
    url: 'selectdata.php',
    data : { 'students': students, 'house':house, 'location':location },
    success: function(data){
      $("#result").html(data);
    }
  });
});

Then your selectdata.php should be like this

<?php 
   $students = $_POST['students'];
   $house = $_POST['house'];
   $location = $_POST['location'];

   //sql query
   $sql = "SELECT * FROM 'mytable' WHERE 'students'= $students AND 'house'= $house AND 'location'= $location;"
?>
Comments