I'm trying to populate new select menu (#school) from db table based on previous selection (#region) with ajax. I wanna get something like that: If there's no result, then hide #school and #class and show only error message. If search. php found results, then show at first school, if school selected too, then show #class.
What's wrong with my ajax POST? it doesn't get anything from db. Please help me to get it work. my js looks like that
$(document).ready(function(){
$("#school").hide();
$("#class").hide();
searchSchool = function(regionSelect){
var selectedRegion = $("select[name*='"+regionSelect.name+"'] option:selected").val();
if (selectedRegion!='0'){
$.ajax({
type: "POST",
url : "core/code/includes/search.php",
data: {region_id: selectedRegion},
success: function(result, status, xResponse){
if (result!=''){
$("#school").show();
$("#class").show();
$("#school").html(result);
$("#error").hide();
}else{
$("#error").html("There is no school found in this region");
$("#school").html('');
$("#school").hide();
}
},
error: function(e){
alert(e);
}
});
}else{
$("#error").html('Please select a region first');
$("#school").html('');
$("#school").hide();
$("#class").hide();
}
}
});
and search.php
<?php
require 'db.php';
if(isSet($_POST['region_id'])) {
$region_id = mysql_real_escape_string($_POST['region_id']);
$res=$db->query("SELECT * FROM schools WHERE id='".$_POST['region_id']."'");
while ($row = $res->fetch_array(MYSQLI_BOTH)) {
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
}
}
?>