I have spent the whole of today trying to figure what is wrong with and I have read a lot of similar problems here but this seems to be a peculiar issue.
I want an AJAX call to fill a dropdown list base on previous selection from MySQL database but it is not working as the POST is not sending any data to PHP $id = $_POST['id'] file I am sending it to. However, if I assign a constant value to it (say $id = 1), it works just fine and return the expected data from the database.
This is the AJAX code:
<script type="text/javascript">
$(document).ready(function()
{
$("#state").change(function()
{
var menuId = $(this).val();
var request = $.ajax({
url: "schools.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$("#schools").html( msg );
});
});
});
</script>
And the PHP code:
<?php
include('../connection.php');
if(isset($_POST['id']) && $_POST['id'] != '')
{
$id = $_POST['id'];
$SQ = "SELECT c_name FROM courses WHERE fac_id = ?";
$q = $conn->prepare($SQ) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $id);
$q->execute();
$total = $q->fetchAll();
$i=1;
foreach ($total as $sch){
echo "<option class = 'option' value = '$i'>". $sch[0].</option>";
$i++;
}
}
?>
EDITTED:
This the HTML code:
<form class="form-horizontal">
<!-- Form Name -->
<!-- Select Basic -->
<div class="control-group">
<label class="control-label" for="selectbasic">State where your school is located</label>
<div class="controls">
<select id="state" name="state" class="form-control input-xlarge">
<?php
$i=1;
$SQ = "SELECT * FROM states";
$schools = $conn->prepare($SQ);
$schools->execute();
$total = $schools->fetchAll();
foreach ($total as $sch){
echo "<option class = 'option' value = '$i'>". $sch[1]. "</option>";
$i++;
}
?>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="control-group">
<label class="control-label" for="selectbasic">School</label>
<div class="controls">
<select name="school" id = 'schools' class="form-control input-xlarge">
<?php
$i=1;
$SQ = "SELECT * FROM schools";
$schools = $conn->prepare($SQ);
$schools->execute();
$total = $schools->fetchAll();
foreach ($total as $sch){
echo "<option class = 'option' value = '$i'>". $sch[1]. "</option>";
$i++;
}
?>
</select>
</div>
</div>
</form>
<select id="state" name="state" class="form-control input-xlarge">on which I want the next drop down be depended on.$sch[0].</option>";should be$sch[0]."</option>";