Skip to content

Instantly share code, notes, and snippets.

@yitsushi
Last active December 10, 2015 04:28
Show Gist options
  • Save yitsushi/4381067 to your computer and use it in GitHub Desktop.
Save yitsushi/4381067 to your computer and use it in GitHub Desktop.
Load new comments
<!-- include all your js + client_with_jquery.js -->
<h1>Post title</h1>
<div>Content</div>
<div id='comments'>
<div class='comment' data-ts='1356537160'>content</div>
<div class='comment' data-ts='1356537142'>content</div>
</div>
var checkChanges = function() {
var ts = jQuery('#comments .comment').first().data('ts');
jQuery.get('/get_new_comments.php?_t=' + ts, function(res) {
if (!res.hasOwnProperty('content')) {
alert('Hiba!');
return false;
}
if (res.content.length > 0) {
var container = jQuery('#comments');
for (var i = 0, _l = res.content.length; i < _l; i++) {
var comment = jQuery(res.content[i]);
container.prepend(comment);
comment.show();
}
}
setTimeout(checkChanges, 500); // 500ms after we run succesfully
}, "json");
}
setTimeout(checkChanges, 500); // 500ms
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
$timestamp = $_GET['_t'];
$post_id = $_GET['_t'];
if ($stmt = $mysqli->prepare("select * from comments where post_id = ? and created_at > ?")) {
$stmt->bind_param('ii', $post_id, $timestamp);
$stmt->execute();
$res = $stmt->get_result();
$stmt->close();
$returnValue = array();
while($row = $res->fetch_assoc()) {
$comment =<<<EOC
<div class='comment' style='display: none;' data-ts='{$row["created_at"]}'>
CONTENT
</div>
EOC;
$returnValue[] = $comment;
}
echo json_encode($returnValue);
} else {
echo "/* ERROR: ";
var_dump($mysqli->error);
echo " */\n";
echo "[]";
}
$mysqli->close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment