I’m having a code problem in the json request generated from php

Asked

Viewed 153 times

1

php query file.

<?php
     //header("Content-Type: application/json; charset-utf8");
     header('Content-Type:' . "text/plain");

    $baseDado = "teste";
    $host = "localhost";
    $user = "rafael";
    $password = "159";
    $ligacao = new PDO("mysql:dbname=$baseDado;host=$host", $user, $password);

    $motor = $ligacao->prepare("SELECT * FROM user");
    $motor->execute();

    if($motor->rowCount()==0){
            echo '<p>Sem Informações no banco de dado user</p>';
    }
    else
        {   
        foreach ($motor as $value) {
                    //$delete = $value['id_user'];
                    echo json_encode($value);
                    //echo '#ID '.$value['id_user'].'<br>';
                    //echo 'Nome '.$value['nome'].'<br>';
                    //echo 'Email '.$value['email'].'<br>';
                    //echo 'Senha '.$value['pwd'].'<br>';
                   // echo '<div>';
                   //     echo '<a href="delete.php?delete='.$delete.'">delete</a>';
                   // echo '</div>';
                   // echo '<hr>';
        }

    }


    $ligacao = null;
?>

I have json data information that was generated from php with the method, json_encode(),

{"id_user":"1","0":"1","email":"[email protected]","1":"[email protected]","nome":"rafael","2":"rafael","pwd":"rafael","3":"rafael"}{"id_user":"2","0":"2","email":"[email protected]","1":"[email protected]","nome":"angela","2":"angela","pwd":"123","3":"123"}{"id_user":"3","0":"3","email":"[email protected]","1":"[email protected]","nome":"ricardo","2":"ricardo","pwd":"000","3":"000"}{"id_user":"4","0":"4","email":"[email protected]","1":"[email protected]","nome":"joao","2":"joao","pwd":"159","3":"159"}{"id_user":"5","0":"5","email":"[email protected]","1":"[email protected]","nome":"bruna","2":"bruna","pwd":"bruna","3":"bruna"}{"id_user":"6","0":"6","email":"[email protected]","1":"[email protected]","nome":"samsung","2":"samsung","pwd":"159357","3":"159357"}

When I do the data requests in the Undefined presentation on the user page code below the script

function bustarItem(){
    var items = "";
    var url = 'consulta.php';
    $.ajax({
        url: url,
        type: 'GET',
        datatype: 'json',
        beforeSend: function(resultado){
            $('.mensagem').html('Carregando');
        },
        success: function(resultado){
            for(var i = 0; i < resultado.length; i++){
                items += resultado[i].nome + '<br>';
            }
            $('.info').html(items);
        },
        fail: function(resultado){
            $('.mensagem').html('ERRO NO CARREGAMENTO');
        },
        complete: function(resultado){
            $('.mensagem').html('Tudo Pronto');
        }
    })
}
  • What’s the problem? you only presented the codes.

  • on the page instead of appearing the information that this in the database appears Undefined

  • You can pass the code that’s in the file php query. ?

  • I just update, see the file there, do not call those who are commented not

  • This code would be a login system?

  • Not this code I’m using it as study, only that the only result that appears to me on the page is Undefined, the method that we use to search information in the database and PDO, only ajax is the only problem for me do not know yet pq appears Undefined

  • Okay, I’ll test the code here, 1 min.

  • blz forehead there to see if you coseguir discovered this error,

Show 3 more comments

1 answer

1


I ran your code here that’s what I did:

/
/index.js         #tem a função "bustarItems()"
/consulta.php     #retorna o suposto "JSON"
/index.html       #chama os arquivos e coloca o resultado nas divs

Your problem is with the JSON being returned. Note.

//ASSIM DEVERIA SER O SEU FOREACH
$resultado = [];
foreach ($motor as $value) {
  $resultado[] = $value;
}
echo json_encode($resultado);

what Voce is doing is: Every foreach is written a json on the screen, separately so there is no comma between them, separating them, then from an error and returns Undefined.

Something else

The function success of Ajax is never returned(with application/json in the.php query), it only goes straight to the complete. Because Ajax expects a application/json comes a application/json but an invalid answer, not a valid JSON, should have commas between each object, something like:

[ #dentro de um array
    {"nome":"Fulaninho"},    #com virgula
    {"nome":"Fulaninha"}
]

mass. if Voce runs it will get an error in JSON.parse()

//no consulta.php, tem header("content-type: text/plain");
function bustarItem(){
    var items = "";
    var url = 'consulta.php';
    $.ajax({
        url: url,
        type: 'GET',
        datatype: 'json',
        beforeSend: function(resultado){
            $('.mensagem').html('Carregando');
        },
        success: function(resultado){
        },
        fail: function(resultado){
            $('.mensagem').html('ERRO NO CARREGAMENTO');
        },
        complete: function(response){
            $('.mensagem').html('Tudo Pronto');

            var resultado = response.responseText
            console.log(JSON.parse(resultado)); //ERRO <<<<<
            for(var i = 0; i < resultado.length; i++){
                items += resultado[i].nome + '<br>';
            }
            $('.info').html(items);
        }
    })
}    
bustarItem();

Like I said, error in consulta.php, do as I did.

Tip:

In the.php query, instead of a foreach, you could put something like.

$resultado = $resultado->fetchAll(PDO::FETCH_OBJ);
echo json_encode($resultado);

Notice that in your JSON are repeated values with different keys, look:

    id         id       email                    email
{"id_user":"2","0":"2","email":"[email protected]","1":"[email protected]"}
  • our flw bro even, did really work out

Browser other questions tagged

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