简体   繁体   中英

Using setInterval to refresh page

I am attempting to create a setInterval function to check for new comments, select and post them. So far, it is 'sort-of' working, but not how I want it to. What it is doing is every three seconds re-posting all of my comments instead of just refreshing them.

What am I doing wrong for this to not just refresh the comments?

HTML

<form action="" method="POST" id="comment-form">
            <textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
            <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
            <input id="comment-button" name="submit" type="submit" value="Post">
        </form>
        <div id="comment-container">

AJAX

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 {
                $('#comment-container').prepend(data);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + " | " + errorThrown);
            console.log("error"); //otherwise error if status code is other than 200.
        }
    });


}
setInterval(commentRetrieve, 300);

PHP

$user = new User();

    $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();
    //$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);  
    //$comment_array = array();
    $rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $row) {
        $comment_id = $row['id'];
        $comment_user_id = $row['user_id'];
        $comment_username = $row['username'];
        $home_comments = $row['comment'];
        $comment_date = $row['date'];
        $commenter_user_id = $row['user_id'];
        $commenter_img = $row['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">';
            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>';
        }   
    }
}

It's because when you have comments you print new one. What i suggest to do is use JSON to get the comments array, pass an ID to each comment and check if the Id is allready present in the list. that way you only paste new comment, here's an example.:
html

<form action="" method="POST" id="comment-form">
        <textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
        <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
        <input id="comment-button" name="submit" type="submit" value="Post">
    </form>
    <div id="comment-container">
        <div id="comment-1">bla bla bla</div>
    </div>


js

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);
            $(array).each(function($value) {
                if($('#comment-container').find('#comment-' + $value.id).length == 0) {
                    $('#comment-container').prepend($value.html);
                }
            });
        }
    },
    error: function (xhr, textStatus, errorThrown) {
        alert(textStatus + " | " + errorThrown);
        console.log("error"); //otherwise error if status code is other than 200.
    }
});


}
setInterval(commentRetrieve, 300);


PHP

$user = new User();

$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();
//$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);  
//$comment_array = array();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $comment_id = $row['id'];
    $comment_user_id = $row['user_id'];
    $comment_username = $row['username'];
    $home_comments = $row['comment'];
    $comment_date = $row['date'];
    $commenter_user_id = $row['user_id'];
    $commenter_img = $row['img'];
    $commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
    if ($home_comments === NULL) {
        echo 'No comments found.';
    } else {
        $html = "";
        $html .= '<div class="comment-post-box">';
        $html .= $commenter_img;
        $html .= '<div class="comment-post-username">'.$comment_username. '</div>';
        $html .= '<div>'.$comment_date. '</div>';
        $html .= '<div class="comment-post-text">'.$home_comments. '</div>';
        $html .= '</div>';
        array('id' => $comment_id, 'html' => $html) 
    }   
}
}


For better improvement, i would suggest looking into NodeJs socket for more realtime update. Here's a few link.

Official NodeJs Website
Official SocketIo Website
Chat tutorial with socketIo and Nodejs
Hope it helps!

  • Nic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM