Fill in INPUTS with ajax

Asked

Viewed 2,632 times

1

I have some fields that I need to fill with AJAX of a SELECT in php.

I am already able to fill in the ID field, and CLIENT, now I have to fill in the rest of the items, such as ENDERECO, CPF, BAIRRO, CIDADE.

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);
      }    
    });

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>
  • Hello Alh! And what is the problem that is happening?

  • Hello @Dvd, I am filling the input CLIENT and ID, with ajax coming from php, now missing fill more INPUTS as city, address in the same way.

  • But there’s some mistake?

  • @Dvd no, this working however only fills the input Cliete and Id_client, I need to fill the other inputs remaining

1 answer

1


Your query of mysql is only seeking ID,NOME, for it to return more results need to enter them in your search or use a joker * return all these data, example exchanges your query:

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

For

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

or this returns only the columns you want

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

And no while you need to fill the array which will be returned via json

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

In part html you need to adjust your need.

Considerations of your code

He’s getting the result of the tag <a who belongs to the class resultado_json and there’s the attribute alt that is receiving the value for the key key, and the attribute id belonging to the same class that receives the value of chave

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

  • This way the array construction was 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 in the answer you will see that I changed the shape of the array to return a collection of keys, thus staying:

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

Now on the each of json, we have some observations:

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

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

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

To get around this problem you must change the way to return this data.

__In the success of json you create the results this way

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

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

Here I’ll 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);
  • Hello, and in the json there where I am picking up the CLIENT and ID_CLIENTE , I do not know if it is just to take the data because it seemed to me that it is set to pick up by the (id, and alt) var code_p = $(this). attr('id'); var name_p = $(this). attr('alt');

  • here on this line also seems to me to be catching by key (alt) and value (id)

  • I’m trying to understand your javascript code but each has only one result and next sequence is confused, you from Hide and then delete the content html(' ')?

  • You don’t have to look at it, because it has another function that is to return the result of the select data with the results of registered customers, but it is not belonging to this function of this question of the question in question.

  • I edited the answer and explained step by step how to solve the problem, but as I do not know your database I used generic names need to pay attention to the correct names and if they are equal, case sensitive

  • Thanks buddy, I got here with your help!! It’s people so this forum needs, thank you!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.