Klapsius Klapsius - 1 month ago 4x
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:

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


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



And test1.php file

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'],
echo json_encode($values);

and part of HTML:


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


And system return back only:

undefined undefined
undefined undefined


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(

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