Paul Paul - 1 month ago 8
Javascript Question

JSON data from php not outputting

I am running into an issue getting JSON data that is sent from a php file to output onto my page. What I am trying to do is create a commenting system, so whenever someone makes a comment, my AJAX code gets the SELECT query results and reloads the already listed comments, essentially to show new comments, whether the user posted it or someone else did.

What I have is three files, the comments page, AJAX, and PHP files. I do a

SELECT
query initially on the comments page to get the data on page load, then I want the same set of comments to consistently load every three seconds.

The
setInterval()
is working and the JSON is being sent over, as I see it within my console, but it isn't actually refreshing and outputting. In addition, I really only want the comments to reload if there has been a new comment created, rather than the comments reloading just to reload.

Does anyone seeing what I am doing wrong for the JSON data to not output?

Here is how I initially get the output on the page load. This is solely using the php on the comments page.

<div id="comment-container">
<?php
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";

if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
$select_comments_stmt->execute();
if (!$select_comments_stmt->errno) {
//echo "error";
}
$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
//var_dump($select_comments_stmt);
$comment_array = array();
while ($select_comments_stmt->fetch()) {
$comment_array[] = $comment_user_id;
$comment_array[] = $comment_username;
$comment_array[] = $home_comments;
$comment_array[] = $comment_date;
$comment_array[] = $commenter_user_id;
$comment_array[] = $commenter_img;
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
echo '<div class="comment-post-box" id="comment-'. $comment_id .'">';
//echo '<div class="comment-post-box" id="comment-'.$row['id'].'">';
echo $commenter_img;
echo '<div class="comment-post-username">'.$comment_username. '</div>';
echo '<div>'.$comment_date. '</div>';
echo '<div class="comment-post-text">'.$home_comments. '</div>';
echo '</div>';
}
}
}
?>
</div>


The PHP to SELECT from the home_comments table and echos the JSON

$user = new User();

//Get the last insert id
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";

if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
$comments = array();
foreach ($rows as $row) {

$html = "";
//$html .= '<div class="comment-post-box">';
$html .= '<div class="comment-post-box" id="comment-'.$row['id'].'">';
$html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
$html .= '<div class="comment-post-username">'.$row['username']. '</div>';
$html .= '<div>'.$row['date']. '</div>';
$html .= '<div class="comment-post-text">'.$row['comment']. '</div>';
$html .= '</div>';
$data = array('id' => $row['id'], 'date' => $row['date'], 'html' => $html);
$comments[] = $data;
}
}
echo json_encode($comments);


Then my AJAX to attempt to refresh the list of comments:

function commentRetrieve(){

$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
//console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
var array = JSON.parse(data);
console.log(data);
$(array).each(function(this) {
if($('#comment-' + this.id).length == 0) {
$('#comment-container').prepend(this.html);
console.log(this.html);
}
});
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});


}
setInterval(commentRetrieve, 3000);


Edit: DATA sent over

[{id: "51", date: "2016-10-26 09:25:42",…}, {id: "22", date: "0000-00-00 00:00:00",…},…]
0
:
{id: "51", date: "2016-10-26 09:25:42",…}
1
:
{id: "22", date: "0000-00-00 00:00:00",…}
2
:
{id: "21", date: "0000-00-00 00:00:00",…}
3
:
{id: "20", date: "0000-00-00 00:00:00",…}
4
:
{id: "19", date: "2016-10-23 09:56:08",…}
5
:
{id: "18", date: "2016-10-21 09:51:35",…}
6
:
{id: "16", date: "2016-10-20 14:41:10",…}
7
:
{id: "15", date: "2016-10-20 13:23:30",…}
8
:
{id: "12", date: "2016-10-20 09:10:28",…}
9
:
{id: "11", date: "2016-10-19 23:54:58",…}
10
:
{id: "10", date: "2016-10-19 23:41:52",…}
11
:
{id: "9", date: "2016-10-19 23:41:52",…}
12
:
{id: "8", date: "2016-10-19 23:41:16",…}


Where I received ^^

enter image description here

enter image description here

Answer

Small working example:

var count = 0;
var RETRIEVE_INTERVAL = 1000;
var datas = [ '[{"id": "51", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-51\\">51</div>"}]'
            , '[{"id": "22", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-22\\">22</div>"}]'
            , '[{"id": "5", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-5\\">5</div>"}]'
            , '[{"id": "34", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-34\\">34</div>"}]'
            , '[{"id": "51", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-51\\">51</div>"}]'
            , '[{"id": "10", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-10\\">10</div>"}]'
            , '[{"id": "70", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-51\\">70</div>"}]'
            , '[{"id": "22", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-22\\">22</div>"}]'
            , '[{"id": "40", "date": "2016-10-26 09:25:42", "html": "<div id=\\"comment-40\\">40</div>"}]'
            ];

function commentRetrieve(){
    // mock data retrieval
    if (count == datas.length)
        return;
    var data = datas[count++];

    var array = JSON.parse(data);
    $(array).each(function() {
        if($('#comment-' + this.id).length == 0) {
            $('#comment-container').prepend(this.html);
        }
    });

    setInterval(commentRetrieve, RETRIEVE_INTERVAL);
}

$(commentRetrieve);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div id="comment-container" id="intro-box">
    <div id="comment-5">5</div>
    <div id="comment-10">10</div>
  </div>
</body>