2
I’m using the help of a post here in the OS.
The difference is that instead of having several options to choose in the other combobox, I only have one option in the bank, which should already be inserted in the input, when selecting the related.
The code I’m using:
<?php include 'conn.php'; ?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Combos Dependentes</title>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
</head>
<body>
<select id="CmbUF">
<option value="">Selecione a UF</option>
<?php
foreach($pdo->query('SELECT ufid, uf FROM ufs order by uf') as $row){
echo '<option value="'.$row['ufid'].'">'.$row['uf'].'</option>';
}
?>
</select>
<select id="CmbCidade">
</select>
<script type="text/javascript">
$(document).ready(function() {
$('#CmbUF').change(function(e) {
$('#CmbCidade').empty();
var id = $(this).val();
$.post('call_cidades.php', {ufid:id}, function(data){
var cmb = '<option value="">Selecione a Cidade</option>';
$.each(data, function (index, value){
cmb = cmb + '<option value="' + value.cidadeid + '">' + value.cidade + '</option>';;
});
$('#CmbCidade').html(cmb);
}, 'json');
});
});
</script>
</body>
</html>
DO Call Cities.php:
<?php
if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest"){
include 'conn.php';
$ufid = filter_input(INPUT_POST, 'ufid', FILTER_SANITIZE_NUMBER_INT);
if ($ufid){
$query = $pdo->prepare('SELECT cidadeid, cidade FROM cidades where ufid=? ORDER BY cidade');
$query->bindParam(1, $ufid, PDO::PARAM_INT);
$query->execute();
echo json_encode($query->fetchAll());
return;
}
}
echo NULL;