Searching Array of variables via Ajax and inserting in their due inputs of a form

Asked

Viewed 29 times

2

I have a form that searches and fills, via ajax, the name of the person and year of birth (in their respective fields), all this from the Cpf typed by the user.

It’s something like this:

Digite o CPF do usuário ______________  <button>BUSCAR DADOS</button>

NOME _________________________

DATA DE NSACIMENTO __________________

With this, two requests are made as follows:

$('#botao').click(function(){

        //BUSCA NOME
        $.get('buscar_nome.php?cpf='+$('#cpf').val(), 

        function(result) {
        $('#nome').val(result);
        });

        //BUSCA DATA DE NASCIMENTO
        $.get('buscar_data_nascimento.php?cpf='+$('#cpf').val(), 

        function(result) {
        $('#datanascimento').val(result);
        });

PHP pages are with the following logic:

search_name.php

$cpf = $_GET['cpf'];
$sq1 = select * from tabela where cpf = '$cpf';
$registro = myslq_fetch_array($sq1);

echo registro['nome'];

buscar_data_nascimento.php

$cpf = $_GET['cpf'];
$sq1 = select * from tabela where cpf = '$cpf';
$registro = myslq_fetch_array($sq1);

echo registro['datanascimento'];

It works perfectly, however, I would like to optimize the search of this data (name and date of birth) using only one request. I imagine I should use Array. How should I proceed?

  • you can use a JSON object tb face, it is interesting for the practicality, it has "indices" with name so it is easier to access in my design.

1 answer

1

You can do something like this.

php search.

$cpf = $_GET['cpf'];
$sq1 = select nome,datanascimento from tabela where cpf = '$cpf';
$registro = myslq_fetch_array($sq1);

header('Content-Type: application/json');
echo json_encode($registro);

And in javascript access as follows

$.get('buscar.php?cpf='+$('#cpf').val(), 

function(result) {
   $('#nome').val(result.nome);
   $('#datanascimento').val(result.datanascimento);
});

Just be careful with that stretch

Where Cpf = '$Cpf'

It is possible to make an Injection sql in this parameter. You must sanitize and validate the parameters that come from the user before putting it in a select that way.

  • Hello Vinicius, it worked. Obgd for help. I’ll do the validations. = D

  • @Luis, if the answer helped you and you want to mark as an answer I thank you =).

Browser other questions tagged

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