Klapsius Klapsius - 2 months ago 7
Ajax Question

JSON data in HTML page in a table

I struggling print all my data from DB to webpage using JSON.
But I not understand logical how it should work.
My JSON script:

<script>
$("document").ready(function() {
$.getJSON("test1.php", function(data) {

$("#div-my-table").text("<table>");

$.each(data, function(i, item) {
$("#div-my-table").append("<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});

$("#div-my-table").append("</table>");

});
});
</script>


And test1.php file

<?php
require_once 'connection.php';

$sql = $conn -> prepare("SELECT * FROM DB_NAME");

$sql -> execute();

while ($row = $sql -> fetch(PDO::FETCH_ASSOC))
{
$values = array('code'=>$row['code'],
'line'=>$row['line']);
}
echo json_encode($values);
?>


and part of HTML:

<body>

<table id="div-my-table">
</table>

</body>


And system return back only:

<table>
undefined undefined
undefined undefined

Answer

If you're expecting multiple rows, you need to gather the results properly. The $values gets overwritten every iteration.

while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
    // add another dimension
    $values[] = array(
        'code'=>$row['code'],
        'line'=>$row['line']
    );                  
}

echo json_encode($values);

Or for just one line:

echo json_encode($sql->fetchAll(PDO::FETCH_ASSOC));

So that they are properly nested.

Then on your JS:

<script type="text/javascript"> 
$(document).ready(function() {

    $.getJSON("test1.php", function(data) {

        var table_rows = '';

        $.each(data, function(i, item) {
            table_rows += "<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
        });

        $("#div-my-table").html(table_rows);

    });

});     
</script>
Comments