getJSON PHP shows no result

Asked

Viewed 825 times

0

I am making a simple query via getJSON, but it is not returning the values to be shown.

Filing cabinet testeJson.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function() {  
    //$("#email").click(function() {

        nome = "listar";
        $.getJSON("testeConexaoMobileJson.php", {acao:nome}, function(json){
            $("#nome").val(json[0].nome);
            $("#email").val(json[0].email);
        });
    //});
});
</script>
</head>

<body>
<h1>Cardápio de Pizzas</h1>
    <div id="email"></div>
    <input type="text" name="nome" id="nome"> 

</body>
</html>

Filing cabinet testMobileJson.php

<?php
$mysqli = new mysqli('localhost','','',''); if($mysqli->connect_error){echo "Erro";exit();}

if($_GET['acao'] == 'listar'){
    header('Content-Type: application/json; charset=utf-8'); 
    $rs = $mysqli->query("SELECT * FROM cadastro");
    $row_rs = $rs->fetch_assoc();
    $row = $rs->fetch_array();  
    $registros = mysqli_num_rows($rs);

    while($campos=mysqli_fetch_array($rs)) { 
        extract($campos); 
        $Array = Array(); 

        $Array[] = Array(
                            "nome"  => "$nome",
                            "email" => "$email",
                        ); 

        $json_encode = json_encode($Array); 
        echo $json_encode; 
    } 


}
?>

Result of the testConexaoMobileJson.php file

Inspector: inserir a descrição da imagem aqui

Upshot:

[{"name":"Tiago","email":"[email protected]"}][{"name":"Tiago","email":"[email protected]"}]

3 answers

4


Your codes are pretty redundant, basically what you need is this:

$rs = $mysqli->query("SELECT * FROM cadastro");

$registros = $rs->num_rows;

$arr = array();
while($row = $rs->fetch_assoc()) { 
    $arr[] = $row;
} 

$json_encode = json_encode($arr); 
echo $json_encode; 

Problems:

$row_rs receives the first query record in an associative array, $row does the same thing except that it receives an array indexed by numbers and an associative. Hint delete the line from the assignment of $row.

$rs = $mysqli->query("SELECT * FROM cadastro");
$row_rs = $rs->fetch_assoc();
$row = $rs->fetch_array();  


 while($campos=mysqli_fetch_array($rs)) { 
    extract($campos); 
    $Array = Array(); 
    $Array[] = Array("nome"  => "$nome", "email" => "$email",); 
    $json_encode = json_encode($Array); 
    echo $json_encode; 
} 

It doesn’t make much sense to use extract() elemine it. Every while turn $array is reset with an empty array, the next line already has a syntax error, Yep a comma left there at the end.

The conversion of the array to json should only be done after the while then all values are converted at once.

If you only want some fields of the tables and not all, change the asterisk by the name of the fields.

Change:

SELECT * FROM cadastro

To:

SELECT nome, email FROM cadastro
  • I agree. That extract there could generate debug weeks without understanding why such a variable is with such value

  • I tested and worked, but appeared all the tables of the comic, how do I show only what I want? Leave the one you created above because it is very useful for other people.

  • I understood, but I asked to give a second example showing only the fields I need, but without using the extract, but doing the right way as shown in the first code.

  • @rray Joia thank you very much.

  • kkkkkkkkkkkkkkkkkkkkkkkkkkkkk, I thought of everything but SELECT, kkkkkk

3

You can only display the data with json_encode outside the while, my friend.

while ($campos = mysqli_fetch_array($rs)) { 

    extract($campos); 

    $Array[] = Array(
        "nome"  => "$nome",
        "email" => "$email",
    ); 


    //  Melhor assim

    $Array[] = $campos;


} 

echo json_encode($Array);
  • I did it and returned no value.

  • Updated response

-1

It may be that you are going to the browser some output after echo. Try terminating PHP like this echo json_encode( $resultado); exit();. In javascript, you can use the following code:

$.post ( url, data, function( response ) {

    // Abra o console do navegador para visualizar esta saída
    console.log( response );

    // Digite seu código aqui

}, 'json' );

// Observe que você pode passar o parâmetro 'json' no final
// para converter a resposta ao invés de usar uma função específica

Browser other questions tagged

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