Populate INPUTS with ajax

1

I have some fields that I need to populate with AJAX from a SELECT in php.

I am already able to fill in the ID field, and CUSTOMER, now the remaining items are missing, such as ENDERECO, CPF, NEIGHBORHOOD, CITY.

Ajax

$("#resultado").hide();
    $("#cliente").keyup(function(){
    var query = $(this).val();
    if($("#cliente").val().length > 2){
     $("#resultado").show();//
     $("#resultado").html("<br><span class='naoEncontrado'>Não encontrado.</span><br><br><span><a onClick='novoCliente(1);'>(+) Cadastrar Novo </a></span>");
     document.getElementById("resultado").style = "height:auto;  margin-top:45px; width:330;";
     $.ajax({       
         type: "POST",
          url: "busca_cliente.php",
         data: {q:query},
         dataType: "json",
         success: function(json){
            var options = "";
            $.each(json, function(key, value){


     options +="<a class='resultado_json' alt='" + value + "' id='" + key + "'>" + value + "</a><br/>";
                     //"<option value='" + key + "'> " + value + "</option>";
                });


$("#resultado").show();
    $("#resultado").html("<br>"+options+"<br><span><a onClick='novoCliente(1);'>(+) Cadastrar Novo</a></span>");

  $(".resultado_json").click(function(){
   var codigo_p = $(this).attr('id');
   var nome_p = $(this).attr('alt');
   $("#id_cliente").val(codigo_p);
   $("#cliente").val(nome_p);
   $("#resultado").hide();
   $("#resultado").html('');
   });
     }
  });
  }else{
      $("#resultado").hide();
      $("#resultado").html('');
      $("#id_cliente").val(0);
      }    
    });

customer.php

    <?php
$consulta = $conn->prepare("SELECT ID,NOME FROM cliente WHERE (NOME LIKE '$cliente' OR CNPJ_CPF LIKE '$cliente')");

$consulta->execute();
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
    // aqui eu mostro os valores de minha consulta
    //$idCliente[] = $linha['ID'];
    //$nomeCliente[] = $linha['NOME'];
    $retorno[ $linha['ID'] ] =  $linha['NOME'];
    //echo "<a href='#' name='$nomeCliente' id='$idCliente' class='procura'>$nomeCliente</a><br/>";
    }

echo json_encode($retorno);
    exit();
?>

INPUTS RECEIVING THE MODIFICATION

    <input type="text" name="cliente" id="cliente">
    <input type="text" name="id_cliente" id="id_cliente">
    <input type="text" name="endereco" id="endereco">
    <input type="text" name="cidade" id="cidade">
    <input type="text" name="cep" id="cep">

<div id="resultado_ajax"></div>
    
asked by anonymous 29.10.2017 / 02:14

1 answer

1

Your query of mysql is only searching ID,NOME , so that it returns more results you need to enter your search or use a * wildcard to return all this data, example exchange your query :

"SELECT ID,NOME FROM cliente WHERE ..."

By

SELECT * FROM cliente WHERE ... //para retornar todas as colunas do banco

or by returning only the columns you want

SELECT ID,NOME,CEP,LOGRADOURO,ETC...,ETC... FROM cliente WHERE ...

And in the while you need to fill in the array that will be returned via json

$retorno[] = array( 'ID' => $linha['ID'] , 'NOME' => $linha['NOME'], 'CEP' => $linha['CEP'], <assim até satisfazer> );

In the html part you need to adjust your need.

  

Considerations for your code

It is taking the result of the <a tag that belongs to the resultado_json class and has the alt attribute that is receiving the value for the key key, and the id attribute belonging to the same class which receives the value of chave

  

In php you have defined that array will have as key $retorno[ $linha['ID'] , and the value being = $linha['NOME'];

  • That way the array construction looks like this:

    $retorno('chave' => 'valor')
    

And since it is only returning in the query these two data will always be the same result, if you analyze the answer you will see that I changed the array form to return a collection of keys,

$retorno(
'ID' => 'VALOR_ID',
'NOME' => 'VALOR_NOME',
'CEP' => 'VALOR_CEP',
...
'COLUNA_BD' => 'VALOR_COLUNA'
);
  

Now in each of json , we have alumno remarks:

  • It is returning the data for a link <a>

    <a class='resultado_json' alt='" + value + "' id='" + key + "'>" + value + "</a>
    

You will always receive the same key and the same value because it was defined this way in the array of php

To work around this problem you should change the way you return this data.

__ No success of json you create results in this way

success: function(json){
$('#id_cliente').val(json.ID);
$('#cliente').val(json.NOME);
$('#cep').val(json.CEP);
$('#rg').val(json.RG);
}

That is $('#<nome_id_input>') and .val(json.Nome) refers to the key set in array do php

Here I will change the array do php to make it easier to understand.

while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
$retorno['ID'] = (string) $linha['ID'];
$retorno['NOME'] = (string) $linha['NOME'];
$retorno['CEP']  = (string) $linha['CEP'];
$retorno['RG']  = (string) $linha['RG'];
}
echo json_encode($retorno);
    
29.10.2017 / 02:42