I was trying to create a commenting system like that uses facebook. I use php and jquery. My code works perfect. User writes something in textarea, comment_1 and post it. Comment_1 appears directly under the textarea successfuly. If i refresh the page I can see comment_1 posted at beginning. If I try to post a new comment (comment_2), then comment_2 appears under comment_1 and again comment_1 under comment_2. For example:
At the begining: comment_1
After refresh and post new comment: comment_1 / comment_2 comment_1 So as you can see, after refresh the page it places comment_2 and under it comment_1, but also keeps comment_1 above them (like keeping comment_1 in its "memory"). If I refresh the page I will get comment_2 comment_1 which is what I finaly want, but how can I do this without refresh? Here is my code:
wall.php
<?php
<script>
$(document).ready(function(){
$("#comment_process").click(function(){
if($("#comment_text").val() != ""){
$.post("comments.php?action=post", { comment: $("#comment_text").val() }, function(data) {
$(".comments").html(data);
$("#comment_text").val("");
});
}
});
});
</script>
<div class="comment_container">
<div class="comment_form">
<textarea id="comment_text" ></textarea>
<input type="button" id="comment_process" value="Post"/>
</div>
</div>
<?php include_once("comments.php");?>
<div class="comments"> </div>
?>
and this is comments.php
<?php
function getComments(){
$comments = "";
// use desc order by date in order to display comments by date
$sql = mysql_query("SELECT * FROM comments ORDER BY comment_date DESC ") or die (mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = " <div class='each_comment'> There are no comments ...</div> ";
}else{
while ($row= mysql_fetch_assoc($sql)){
$comments .= "<fieldset> Stefanos Says : <div class='each_comment'> <small><em> ".$row['comment_date']." </em></small><br />".$row['comment']."</div></fieldset> </br>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query(" INSERT INTO `comments` (comment, comment_date) VALUES ('".$comment."', now()) ");
return true;
}
if((isset($_GET['action'])) && ($_GET['action'] == "post")) {
postComments($_POST['comment']);
}
echo getComments();
?>