I have a comment system written in PHP and JavaScript but each time I post the comment goes to the bottom. How do I make it appear at the top?
Here is my code:
The PHP code:
<?php
$sql = mysql_query( "SELECT * FROM `comments` WHERE perma_id = '$permalink' ORDER BY `date` DESC" );
$count = mysql_num_rows( $sql );
?>
<h2 class="comments"><?php echo $count; ?> Comments</h2>
<div id="flash"></div>
<ol id="update" class="timeline">
<?php
while( $row = mysql_fetch_assoc( $sql ) ) {
$userSql = mysql_query( "SELECT * FROM `members` WHERE `id` = '$row[userid]'" );
$userRow = mysql_fetch_assoc( $userSql );
$name = $userRow[ 'userid' ];
$comment = $row[ 'comment' ];
$cDate = $row[ 'date' ];
$icon = $userRow[ 'icon' ];
?>
<li class="box">
<div class="left"><a href="<?php echo $site_url . '/wall/' . $name; ?>"><img src="<?php echo $site_url . '/' . $icon; ?>"/></a></div>
<div class="right">
<div class="name"><a href="<?php echo $site_url . '/wall/' . $name; ?>"><?php echo $name;?></a> said...</div>
<div class="date"><?php echo date("M d, Y g:i a", $cDate); ?></div>
<div class="clearfix"></div>
<div class="comm">
<div class="inside">
<?php echo $comment; ?>
</div>
</div>
</div>
</li>
<?php
}
?>
The JavaScript code:
$(function() {
$('.com_submit').click(function() {
var comment = $("#comment").val();
var user_id = $("#user_id").val();
var perma_id = $("#perma_id").val();
var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };
if(comment=='') {
alert('Please Give Valid Details');
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="../images/ajax-loader.gif" align="left" /> Loading Comment');
$.ajax({
type: "POST",
url: "../commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:first").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
I have li:first
but it does not make it at the top
Use .prepend()
instead of .append()
Your :first
fade in is working, it's just already visible. But remember that's only a jQuery selector.
.append always goes to the end. i usually copy the contents of the ol, append it to the returned dataString, then put it back in the ol.
Replace .append(html)
with .prepand(html)
I think it is happening because when you call append(html) in your javascript, the output is appended to the end of the update div... of course would be useful if you also post your HTML (the div code)