I was very much in doubt of how to return an array of a php using Jquery, I searched several ways and it was always quite complicated. Then performing some tests I found that it was much easier than I thought. So I decided to share.
I am using my select of my crud, but in case of fetch the mysql information, you put the way q wish.
<button type='button' id='1' class='btn btn-primary' onClick='ModalEditar(this.id)'>Alterar</button>
Here is the Jquery I will use to display in modal.
function ModalEditar(id){
$.post('require/jp/jpvisitantes.php',
{
modalEditar:true,
id:id,
},
function(res){
var arr = $.parseJSON(res);
$('#ModalVisitantes').modal('show'); //exibir no modal primeiro, senão, não exibe os dados
$("#nome").val(arr[0]);
$("#cpf").val(arr[1]);
$("#rg").val(arr[2]);
});
PHP file:
extract($_POST); //recebe todas as informações enviada via post e cria as variaveis automaticamente.
if(isset($modalEditar)){
$visitante=$crud->select('visitantes', 'WHERE id = '.$id);
foreach($visitante as $dt){
$dado[0] = $dt['nome'];
$dado[1] = $dt['cpf'];
$dado[2] = $dt['rg'];
}
echo json_encode($dado); //retorna a variavel dado
}
Modal that will receive the information:
<div class="modal fade" id="ModalVisitantes" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div>Nome:
<input type="text" class="form-control" id="nome" maxlength="90" required>
<input type="hidden" id="id"/>
</div>
<div style="width:50%; float:left; min-width:150px;">CPF:
<input type="text" class="form-control" id="cpf" maxlength="14" required="required">
</div>
<div style="width:50%; float:left; min-width:150px;">RG:
<input type="text" class="form-control" id="rg" maxlength="90">
</div>
<br />
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
what comes out in
console.log(e)
? Press F12 and see in the console tab– Marconi
can ask the question an example of is returned?
– Ricardo Pontual
Puts your string being returned to the question.
– Maycon F. Castro
@Ricardopunctual Edited the Question
– I_like_trains
@Mayconf.Castro I edited the question
– I_like_trains
@Marconi I edited the question
– I_like_trains