I want to create a dynamic dropdown menu that one select is based on the value of another select. I tried so many times and failed. I have the code as follows. Anyone can help me to find out what the problem is.
//template:
<script type="text/javascript">
$(function(){
getSelectVal();
$("#grouptypes").change(function(){
getSelectVal();
});
});
function getSelectVal(){
$.getJSON('<?php echo url_for('group_utilization/GroupModification') ?>', {'grouptypes':$("#grouptypes").val()},function(data){
var groups = $("#groups");
$("option",groups).remove();
$.each(json,function(index,array){
var option = "<option value='"+array['id']+"'>"+array['title']+"</option>";
select.append(option);
});
});
}
</script>
GroupType: <select id="grouptypes">
<?php foreach($grouptypes as $type) : ?>
<?php echo "<option value='" . $type->name . "'>" .$type->name. "</option>"; ?>
<?php endforeach ?>
</select><br />
<br />Result:<span id="list-of-groups"></span>
<br />
Group: <select name="group" id="groups">
</select><br />
Another file for returning database returned value:
if(isset($_GET["grouptypes"])){
$grouptypes = $_GET["grouptypes"];
$query = "SELECT g.name FROM groups g INNER JOIN group_types gt ON(gt.id = g.group_type_id AND gt.name = ?)";
$groups = $db->getResultsForQuery($query, $grouptypes);
echo json_encode($groups);
}
Does your PHP Script sends the appropriate headers for JSON ?
try to put this juste before "echo json_encode($groups);". Eventually put an exit call to avoid extra output.
$groups = $db->getResultsForQuery($query, $grouptypes);
header('Content-type:application/json;charset=utf-8');
echo json_encode($groups);
exit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With