BD data via AJAX

Asked

Viewed 40 times

-1

I have a client bank with ID, NAME, CPF and ADDRESS. I need to retrieve this data via AJAX separately. But I’m not sure how to separate the response data, the script is sending all as a single element.

<script type="text/javascript">
    $.ajax({
    url: "listar.php",
    type: "POST",
    data: "campo1=dado1 & campo2=dado2 & campo3=dado3 & campo4=dado4",
    dataType: "html"

    }).done(function(resposta) {

        console.log(resposta);

    }).fail(function(jqXHR, textStatus ) {
        console.log("Request failed: " + textStatus);

    }).always(function() {
        console.log("completou");
    });
    </script>

Ajax

<?php
include "conexao.inc";
  $result_usuarios = "SELECT * FROM tb_pessoas LIMIT 0,1";
  $resultado_usuarios = mysqli_query($conexao, $result_usuarios);

 while($registro = mysqli_fetch_row($resultado_usuarios)){
    $id=$registro[0];
    $placa=$registro[1];
    $marca=$registro[2];
    $modelo=$registro[3];

    echo $id;
    echo $nome;
    echo $cpf;
    echo $endereco;
 }
?>

DATABASE

<?php
include "conexao.inc";
  $result_usuarios = "SELECT * FROM tb_pessoas LIMIT 0,1";
  $resultado_usuarios = mysqli_query($conexao, $result_usuarios);

 while($registro = mysqli_fetch_row($resultado_usuarios)){
    $id=$registro[0];
    $placa=$registro[1];
    $marca=$registro[2];
    $modelo=$registro[3];

    echo $id;
    echo $nome;
    echo $cpf;
    echo $endereco;
 }
?>

The problem is in receiving the data, I am not knowing declare them in other feasible p pd put in different fields of the system, individually, each variable coming from the BD in a different input place for example.

Thanks qq help.

  • You are returning the data as "loose" strings, there is no way to catch each one. You should return them as a JSON object.

1 answer

0


As Sam said, you should return the result at once, or javascript won’t be able to process the return correctly.

You can do something like:

<?php
include "conexao.inc";
$result_usuarios = "SELECT * FROM tb_pessoas LIMIT 0,1";
$resultado_usuarios = mysqli_query($conexao, $result_usuarios);
$usuarios = [];

while($registro = mysqli_fetch_row($resultado_usuarios)){
    $id=$registro[0];
    $placa=$registro[1];
    $marca=$registro[2];
    $modelo=$registro[3];

    $usuarios[] = [
        'id' => $id,
        'nome' => $nome,
        'cpf' => $cpf,
        'endereco' => $endereco 
    ];
 }

 echo json_encode($usuarios);

?>

This way, you would be assembling the return inside the loop and return the JSON expected by Javascript in a format that it could interpret.

Browser other questions tagged

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