I need to populate related selects with data from the database. The HTML page has a select
with id
'fontes' and a select
with id
'cargos'. The jQuery code right now:
$("#fontes").change(function () {
$.ajax({
type: "POST",
url: "json_cargos_fonte.php",
data: ({fonte: $("#fontes").val()}),
dataType: "json",
success: function(json){
var options = "";
$.each(json, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
});
$("#cargos").html(options);
}
});
});
And the content of json_cargos_fonte.php:
<?php
include ("conexao.php");
header('Content-type: text/json');
$fonte = $_POST['fonte'];
$retorno = array();
$queryCargos = "SELECT * FROM `cargos` WHERE `fonte` = '$fonte' ORDER BY `cargo`";
$resultCargos = $mysqli->query($queryCargos) or trigger_error($mysqli->error."<br>[ $queryCargos]");
while ($row = $resultCargos->fetch_object()) {
$retorno[] = $row->cargo;
}
echo json_encode($retorno);
?>
I already tested putting a manual value instead of '$fonte' and it worked, but passing the value selected in fontes does not work. No option appears, beyond the default option I wrote in the HTML:
<select id="cargos" name="cargos" style="min-width: 250px;">
<option>Selecione um Cargo</option>
</select>