problems with php, json, javascript and mysql

0

I'm trying to get data from mysql to display on html with php using json , but it's going wrong, it brings data but it does not display, if I press f12 it shows data from the database but does not display the data.

follow the code:  index.html

<!DOCTYPE html>
<html>
<head>
  <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
 <script type="text/javascript">
 $(document).ready(function()
 {
 var url="ajax.php";
 $.getJSON(url,function(result){
 console.log(result);
 $.each(result, function(i, field){
 var id=field.id;
 var nome=field.nome;
 $("#listview").append(id+nome);
 });
 });
 });
 </script>
</head>
<body>
 <div class="bar bar-header bar-positive" style="margin-bottom:80px;">
 <a href="index.html" class="button button-clear">Home</a>
 <h1 class="title">Read Database (JSON)</h1>
 </div><br/><br/>
 <ul class="list" id="listview">
 </ul>
</body>
</html>

getDados.php

<?php

function conectar(){

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('BASE','db');

try{
    $conexao = 'mysql:host='.HOST.';dbname='.BASE;
        $conexao = new PDO($conexao, USER, PASS);
        $conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        // echo 'Conectado com sucesso';
} catch (PDOException $erro){
    echo $erro->getMessage();
}

return $conexao;
}
?>

ajax.php

<?php
header('Content-Type:' . "text/plain");
include_once "getDados.php";
$pdo = conectar();

    $listar = $pdo->query("select * from cad_cliente");
    $listar->execute();


echo json_encode($listar->fetch(PDO::FETCH_OBJ));


?>
    
asked by anonymous 28.10.2016 / 21:21

1 answer

0

If the return in console is shown it might not be returning an object ... try to see what type of element it is returning.

console.log(typeof result);

If it is of type string and is in the form of JSON , just do parse with JSON.parse and then use ex:

 var result = JSON.parse(result);

This will convert a string in the format JSON to an object javascript of it you can proceed normally.

    
28.10.2016 / 22:02