0
jQuery
$("#idRede").on("change", function () {
$.ajax({
url: "_scripts/_php/_validacoes/buscarDadosRegioes.php",
type: "POST",
dataType: "json",
data: {
idRede: $("#idRede").val()
},
beforeSend: function() {
$("#imgCarregando").css('display','block');
},
success: function (result) {
$("#imgCarregando").css('display','none');
if (result == null){
$("#idRegiao").append("<option value=>Sem Regiões</option>");
} else {
result.forEach(function(option){
$("#idRegiao").append("<option value=" + option["idRegiao"] + ">" + option["nome"] + "</option>")
});
}
}
});
});
searchDadosRegioes.php
<?php
require_once "../../../config.php";
$regioes = $regioesDao->pesquisaRegioesParametro("idRede", $_POST["idRede"]);
$options = null;
$i = 0;
if ($regioes != null) {
foreach ($regioes as $regiao):
$options[$i]["idRegiao"] = $regiao->getIdRegiao();
$options[$i]["nome"] = $regiao->getNome();
$i++;
endforeach;
}
echo json_encode($options);
?>
When the array $redes
returns null
, the line echo json_encode($options);
returns null
.
And, analogously, when the return is a object array, then the php returns a object array. Nothing unusual so far.
The problem is in jQuery that when the result is null
(tested with Alert), then jQuery continues to populate the select with the old data of a previous query that brought more result to the line when the result of null
.
Where is the error?
Looks like he’s going to keep the appends
previous and summing up all.