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

1

file query.php

<?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 request the data in the undefined presentation on the user page code below 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');
        }
    })
}
    
asked by anonymous 06.02.2018 / 20:39

1 answer

1

I ran your code here and this is 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. Repair.

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

What you are doing is: Each foreach is written a json on the screen, separately so there is no comma between them, separating them, then an error and returns undefined. >

Something else

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

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

mass .. if you execute you 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();

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

Tip:

In query.php, instead of a foreach, I could put something like this.

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

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

    id         id       email                    email
{"id_user":"2","0":"2","email":"[email protected]","1":"[email protected]"}
    
06.02.2018 / 21:09