jquery function $ .post or $ .get

-1

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

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

echo $conteudo['id'];

With ajax playing the return coming from the select (which can contain multiple lines) set everything from the array and just get in the answer .. echo json_encode($array);

How can I return an array that can contain multiple rows and get 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, what if I have 100 lines? How can I do the same as ajax .. mount a loop and go through resposta[cont].name .. resposta[cont].idade .. anyway ..

    
asked by anonymous 04.03.2017 / 22:30

1 answer

1

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

  

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

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

To make a loop in the response that the server will send you can use the $.each function of 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);

Comments:

  • I recommend to search a bit about HTTP verbs, because in your example it would be more appropriate if you use the $.get function of jquery, because it represents the HTTP GET verb. And more specifically, how you want to handle a JSON, use the $.getJSON function that jquery provides.

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

  • Well, I hope I have helped. :)

        
    04.03.2017 / 23:23