I have a reaction system made in ajax. So when a user posts a reaction, it is handled by an ajax request and shows the reaction immediately.
Right now, he places the new reactions (added by the ajax request) under the initial loaded reactions. But the initial loaded reactions are queried from the database in a DESC order, so the new reactions have to be place above the initial loaded reactions. My code:
HTML:
<div id="messages">
<?
$sql = "SELECT *
FROM items_comments, users
WHERE items_comments.item_id = '".$id."'
AND items_comments.user_id = users.user_id
ORDER BY comment_id DESC";
$result = $Db->sQuery($sql);
while($row = mysql_fetch_array($result)){
?>
<div id="com_loaded">
<div id="com_loaded_height"></div>
<div id="com_loaded_userpic"><a href="#" class="tooltip"><img src="<?=$row['user_pic']?>" class="img_poster" /><span><?=$row['user_name']?></span></a></div>
<div id="com_loaded_content">
<div id="com_loaded_poster"><a href="#"><?=$row['user_name']?></a></div>
<div id="com_loaded_text"><?=$row['comment_text']?></div>
</div>
<div id="com_loaded_divide"></div>
</div>
<?
}
?>
</div>
JS:
$(function() {
$(".submit-comment").click(function() {
var text = $(".txtinput").val();
var itemid = "<?=$id?>";
var userid = "<?=$_SESSION['user_id']?>";
var dataString = 'text=' + text + '&userid=' + userid + '&itemid=' + itemid;
if(text == '') {
$('#content_error1').fadeIn(250);
$('#content_error1').delay(1500).fadeOut(500);
} else {
$.ajax({
type: "POST",
url: "/ajax/comments.php",
data: dataString,
success: function(html){
$("#messages").append(html);
}
});
}
return false;
});
});
PHP script Ajax calls
<? session_start();
require_once("../include/database.php");
$Db = new Database();
$text = $Db->escape($_POST['text']);
$itemid = $_POST['itemid'];
$userid = $_POST['userid'];
$date = date('Y-m-d');
$sql = "SELECT comment_id
FROM items_comments
ORDER BY comment_id DESC LIMIT 1";
$result = $Db->sQuery($sql);
$row = mysql_fetch_array($result);
$comment_id = ($row['comment_id'])+1;
$sql = "INSERT INTO items_comments (comment_id, item_id, user_id, comment_date, comment_text)
VALUES('$comment_id', '$itemid', '$userid', '$date', '$text')";
$Db->uidQuery($sql);
$sql = "SELECT *
FROM items_comments, users
WHERE items_comments.comment_id = '".$comment_id."'
AND items_comments.user_id = users.user_id
ORDER BY comment_date DESC";
$result = $Db->sQuery($sql);
$row = mysql_fetch_array($result);
$Db->closeConnection();
?>
<div id="com_loaded">
<div id="com_loaded_height"></div>
<div id="com_loaded_userpic"><a href="#" class="tooltip"><img src="<?=$row['user_pic']?>" class="img_poster" /><span><?=$row['user_name']?></span></a></div>
<div id="com_loaded_content">
<div id="com_loaded_poster"><a href="#"><?=$row['user_name']?></a></div>
<div id="com_loaded_text"><?=$row['comment_text']?></div>
</div>
<div id="com_loaded_divide"></div>
</div>
Use
prepend():