jquery function $.post or $.get

Asked

Viewed 358 times

-1

Instead of using ajax for feedback, I’m seeing the jQuery function $.post or $.get.

But I can only return with an echo one column of the mysql table. ex.

echo $conteudo['id'];

With ajax playing the return coming from select (which can contain multiple lines) game all of the array and only caught in the answer.. echo json_encode($array);

How can I return an array that can contain multiple lines and take the function $.post or $.get ?

ex.

$("#idInp").keyup(function(){
    var idd = $("#idInp").val();
    $.post('verifica.php',{id:idd},function(resposta){
        $("#tex").empty();
        if(resposta.trim() == $("#idInp").val() ){
            $("#tex").append("nomes iguais");
        }else{
            $("#tex").append("nomes diferentes");
        }
    });     
});
$seg = $pdo->prepare("SELECT * FROM usuarios WHERE name = :id");
$seg->bindValue(":id",$_POST['id']);
$seg->execute();

$v = $seg->fetch(PDO::FETCH_ASSOC);

echo $v['name'];

if I return only one line (echo $name['name']) will work , plus if I have 100 lines ? How can I do it equal to ajax .. build a loop and go through the resposta[cont].name .. resposta[cont].idade .. at last..

1 answer

1

Okay, from what I understand you want to perform a SELECT in the database, put your records in an array, and then send to the response of an ajax request.

How can I return an array that can contain multiple lines and take $.post or $.get ?

Instead of using fetch(PDO::FETCH_ASSOC), use fetchAll(PDO::FETCH_ASSOC) which will return a two-dimensional associative array, with each Row and its respective columns.

To make a loop in the answer the server will send you can use the function $.each jquery.

Example:

$("#idInp").on('keyup', function(){
    var idd = $(this).val();
    $.getJSON('verifica.php',{id:idd},function(resposta){
        $("#tex").empty();
        $.each(resposta, function (indice, item) {
            if(item.nome == $("#idInp").val() ){
                $("#tex").append("nomes iguais");
            }else{
                $("#tex").append("nomes diferentes");
            }
        });
    });     
});
$seg = $pdo->prepare("SELECT * FROM usuarios WHERE name = :id");
$seg->bindValue(":id",$_GET['id']);
$seg->execute();

$v = $seg->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($v);

Remarks:

  1. I recommend researching a little about HTTP verbs, because in your example it would be more appropriate if you use the function $.get jquery, for representing the verb HTTP GET. And more specifically, as you want to deal with a JSON, use the function $.getJSON that jquery offers.

  2. The $(this) in the example amounts to $("#idInp") because it is within the context of that element.

Well, I hope I helped. :)

Browser other questions tagged

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