user7988893
user7988893

Reputation:

Why can't show data passed by getJSON?

The test-json.php read the database , and prepare it in JSON format.

<?php
$conn = new mysqli("localhost", "root", "xxxx", "guestbook"); 
$result=$conn->query("select * From lyb limit 2"); 
echo '[';
$i=0;
while($row=$result->fetch_assoc()){  ?>
 {title:"<?= $row['title'] ?>",
        content:"<?= $row['content'] ?>",
        author:"<?= $row['author'] ?>",
        email:"<?= $row['email'] ?>",
        ip:"<?= $row['ip'] ?>"}
<?php 
if(
$result->num_rows!=++$i) echo ',';   
}
echo ']'    
?>

For my database,select * From lib limit 2 get the records.

title    | content   | author   | email            |ip
welcome1 | welcome1  | welcome1 | [email protected] |59.51.24.37
welcome2 | welcome2  | welcome2 | [email protected] |59.51.24.38

php -f /var/www/html/test-json.php

[ {title:"welcome1",
         content:"welcome1",
        author:"welcome1",
         email:"[email protected]",
        ip:"59.51.24.37"},
{title:"welcome2",
         content:"welcome2",
        author:"welcome2",
         email:"[email protected]",
        ip:"59.51.24.38"}]

test-json.php get some data in JSON format.

Now to callback the data and show it in the table.

<script src="http://127.0.0.1/jquery-3.3.1.min.js"></script>
<h2 align="center">Ajax show data in table</h2>
<table>
    <tbody id="disp">
        <th>title</th>
        <th>content</th>
        <th>author</th>
        <th>email</th>
        <th>ip</th>
    </tbody>
</table>

<script> 
$(function(){
    $.getJSON("test-json.php", function(data) {
        $.each(data,function(i,item){
            var tr = "<tr><td>" + item.title + "</td>"    +
                        "<td>"  + item.content  + "</td>" +
                        "<td>"  + item.author  + "</td>"  +
                        "<td>"  + item.email  + "</td>"   +
                        "<td>"  + item.ip  + "</td></tr>"
            $("#disp").append(tr);
        });
    });
});
</script>

Type 127.0.0.1/test-json.html, why no data created by test-json.php on a webpage?

What i get is as below:

Ajax show data in table
title   content author  email   ip

What i expect is as below:

Ajax show data in table
title   content author  email   ip
welcome1  welcome1  welcome1  [email protected]  59.51.24.37
welcome2  welcome2  welcome2  [email protected]  59.51.24.38

Upvotes: 1

Views: 74

Answers (2)

ThS
ThS

Reputation: 4783

You have plenty of mistakes in your PHP code.

Here's how things should be handled in the server-side(PHP):

filename: test-json.php

  1. Fetch the records from the database.

  2. Populate an array(I named that array $data in the code below) with the records that are already fetched from the database.

  3. Encode that array as JSON format and echo the result.

Here's how things should be handled in the client-side(JavaScript):

  1. Make an AJAX request to the test-json.php file.

  2. If that request has succeeded, then iterate over the returned JSON and populate a variable(I named it 'html') that will hold all the HTML code(along with the received data) that will be appended to the table.

  3. Append that variable(that I named 'html') to the table, with that we gain performance as we access the DOM only once per AJAX request.

With all that being said, here's the solution:

PHP code - filename: test-json.php:

<?php
// use the column names in the 'SELECT' query to gain performance against the wildcard('*').
$conn = new MySQLi("localhost", "root", "xxxx", "guestbook"); 

$result = $conn->query("SELECT `title`, `content`, `author`, `email`, `ip` FROM `lyb` limit 2"); 

// $data variable will hold the returned records from the database.
$data = [];

// populate $data variable.
// the '[]' notation(empty brackets) means that the index of the array is automatically incremented on each iteration.
while($row = $result->fetch_assoc()) {
  $data[] = [
    'title'   => $row['title'],
    'content' => $row['content'],
    'author'  => $row['author'],
    'email'   => $row['email'],
    'ip'      => $row['ip']
  ];
}

// convert the $data variable to JSON and echo it to the browser.
header('Content-type: application/json; charset=utf-8');
echo json_encode($data);

JavaScript code

$(function(){
    $.getJSON("test-json.php", function(data) {
        var html = '';
        $.each(data,function(key, value){
            html += "<tr><td>" + value.title + "</td>"    +
                        "<td>"  + value.content  + "</td>" +
                        "<td>"  + value.author  + "</td>"  +
                        "<td>"  + value.email  + "</td>"   +
                        "<td>"  + value.ip  + "</td></tr>";

        });
        $("#disp").append(html);
    });
});

Learn more about json_encode function.

Hope I pushed you further.

Upvotes: 1

Phil
Phil

Reputation: 164911

The problem is the response from your PHP script is not valid JSON.

In JSON, object keys must be quoted.

Rather than try and roll-your-own JSON response, use json_encode() to do it for you. For example

<?php
$conn = new mysqli("localhost", "root", "xxxx", "guestbook"); 
$stmt = $conn->prepare('SELECT title, content, author, email, ip FROM lyb limit 2');
$stmt->execute();
$stmt->bind_result($title, $content, $author, $email, $ip);
$result = [];
while ($stmt->fetch()) {
    $result[] = [
        'title'   => $title,
        'content' => $content,
        'author'  => $author,
        'email'   => $email,
        'ip'      => $ip
    ];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
exit;

You don't have to use prepare() and bind_result(), that's just my preference when working with MySQLi.

This will produce something like

[
  {
    "title": "welcome1",
    "content": "welcome1",
    "author": "welcome1",
    "email": "[email protected]",
    "ip": "59.51.24.37"
  },
  {
    "title": "welcome2",
    "content": "welcome2",
    "author": "welcome2",
    "email": "[email protected]",
    "ip": "59.51.24.38"
  }
]

Upvotes: 1

Related Questions