0
I got the following HTML
:
<label class="labelPequeno" for="idPastor">Pastor</label> :
<select name="idPastor" id="idPastor" class="inputTextMedio required">
<option value="" selected>Escolha o Pastor</option>
<?php
if ($pastores == null) echo "<option value=''>Sem Pastor</option>";
else {
foreach ($pastores as $pastor) echo "<option value=".$pastor["idPastor"].">".$pastor["nome"]."</option>";
}
?>
</select> <br/>
<label class="labelPequeno" for="idRede">Rede</label> :
<select name="idRede" id="idRede" class="inputTextMedio required">
<option value="" selected>Escolha o Pastor primero</option>
<div class="optionsRedes"></div>
</select> <br/>
The goal now is to fill the combo select idRede
with the result of $.ajax
$(document).ready(function (e) {
$("#idPastor").on("change", function () {
$.ajax({
url: "_scripts/_php/_validacoes/buscarDados.php",
type: "POST",
dataType: "json",
data: {
idPastor: $("#idPastor").val()
},
beforeSend: function() {
$("#imgCarregando").css('display','block');
},
success: function (result) {
alert(result);
$("#imgCarregando").css('display','none');
$(".optionsRedes").html(result);
}
});
});
});
But the div
receives no value whatsoever.
Where am I going wrong?
Obs.: when I do:
alert(result);
I get back from options
correctly.
<option value=1>Rede 1</option><option value=2>Rede 2</option>
That won’t work, you need to do the
append
but in theselect
. Try it like this:$("#idRede").append(result);
and see if that’s already answered– Ricardo Pontual
worked! But, what would be right? 1) Loop and append each option or append the 2 options as a string?]
– Carlos Rocha
depends on how you receive the data. If you already receive html, it is OK to append directly to html content. If you received a
json
, then it would be better to loop and add the items one by one. If it were to start now this code, would say to return ajson
with the data and mount the options and add one by one. The server side returns "data" and the client side mounts as needed on the page. That opinion of mine ;-)– Ricardo Pontual
better do it your way. It seems more correct. PHP = Data. If you want to post as an answer I accept!
– Carlos Rocha
published an answer with the solution to the append of options
– Ricardo Pontual
Just to clarify that you have written invalid HTML. The element
<select>
accepted only<option>
or<optgroup>
as children, then his<div>
would be a problem anyway (Docs)– fernandosavio