3
Hello, I’m doing the famous combo of state carries city. Everything is working perfectly, as I will debug in my script, until the moment that must change the value of select (options returned from the function). Follow my code (index.php):
<div class="form-group">
<label class="col-md-4 control-label col-xs-12" for="Endereco">Endereço*</label>
<div class="col-md-1 col-xs-4">
<select class="selectpicker" data-width="auto" id="estado" name="estado">
<?php
$query = "SELECT SIGLA, CODIGO FROM estado ORDER BY TX_SIGLA";
$result = mysqli_query($conectar, $query);
while ($resultado = mysqli_fetch_assoc($result)) { ?>
<option value="<?php echo $resultado['CODIGO']; ?>"><?php echo $resultado['SIGLA']; ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-3 col-xs-4">
<select data-width="auto" id="municipio" name="municipio" class="selectpicker">
<option value="0" disabled="disabled">Escolha o estado</option>
</select>
</div>
</div>
Code (city.php):
<?php
if (isset($_POST["cd_estado"])) {
$cod_estado = $_POST["cd_estado"];
$query = "SELECT NOME, CODIGO FROM municipio WHERE ESTADO = '$cod_estado' ORDER BY NOME";
$result = mysqli_query($conectar, $query);
while ($resultado = mysqli_fetch_assoc($result)) {
echo '<option value="' . $resultado['CODIGO'] . '">' . $resultado['NOME'] . '</option>';
}
} else {
echo "<option value='0'> Sem cidade </option>";
}
?>
Script:
<script>
$(document).ready(function() {
$("#estado").change(function() {
$("#municipio").html('<option value="0">Carregando...</option>');
var est = document.getElementById("estado").value;
$.ajax({
type: 'post',
url: 'cidade.php',
data: {
cd_estado: est
},
success: function(data) {
document.getElementById("municipio").innerHTML = data;
console.log(data);
}
});
});
});
</script>
I have tried to change the value of select "municipality" with the following alternatives:
$("#municipio").html(data);
$("#municipio").append(data);
document.getElementById("municipio").innerHTML = data;
$("select[name=municipio]").html(data);
None works. But in "console.log(data);" the value is being returned correctly. What am I doing wrong?
How is the return coming
data
in the Ajax function?<option value="codigo_cidadex">Cidade X</option>
?– Maurivan
Yes, it is returning correctly. My problem is not being able to change the content of Div. Not even with the value
<option value="codigo_cidadex">Cidade X</option>
within the script itself.– DryAlves
I’m thinking it might be something with Bootstrap itself, but I still don’t know what it is. Because I tested my code on a clean page, no framework, and it works in every way.
– DryAlves