problems with php, json, javascript and mysql

Asked

Viewed 50 times

1

I’m trying to get data from mysql to display on html with php using json, but this going wrong, it brings the data but does not display, if I hit the F12 it shows the database data but does not display the data.

follows 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));


?>
  • Ask the question what is the result of ajax...

  • It shows the data in the console.log?

1 answer

0

If it shows the return on the console you may not be returning an object... try to see what kind of element is returning.

console.log(typeof result);

If you’re the type string and is in the format of JSON just do the parse with JSON.parse and then use ex:

 var result = JSON.parse(result);

This will convert a string into the format JSON for an object javascript so you can proceed normally.

Browser other questions tagged

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