I am creating a post and comment functionality in my website. I am using Ajax and PHP for the purpose. But there seems to be a bit problem. When ever I add a comment, it is always added to the first post. I have to reload the page to get all the comments in their respective posts. I created the ajax code to prevent the dependence on reloading, but it seems like ajax is not working correctly.
<script type="text/javascript">
function postComment(id) {
var cuser = $("#uid" + id).val();
var cdetail = $("#detail" + id).val();
var cpost = $("#post" + id).val();
var dataString = 'cuser='+ cuser + '&cdetail=' + cdetail + '&cpost=' + cpost;
if (cdetail == '') {
alert('Please Give Valid Details');
} else {
$.ajax({
url: "index.php?mod=Comment&do=comment",
data: dataString,
type: "POST",
success: function(resp) {
document.getElementById('rslt').innerHTML = resp;
},
error: function(e) {
alert('Error: '+ JSON.stringify(e));
}
});
}
}
</script>
<div align="center" style="background-color:#f6f7f8;">
<table width="98%">
<form method="post">
<tr>
<td>
<textarea rows="1" id="detail<?php echo $i ?>" class="form-control" name="detail" style="width:100%; resize:none;" placeholder="Add comment"></textarea>
</td>
</tr>
<tr>
<td align="center">
<input type="hidden" id="uid<?php echo $i ?>" name="uid" value="<?php echo $uid ?>">
<input type="hidden" id="post<?php echo $i ?>" name="post" value="<?php echo $getPosts_pId ?>">
<input type="button" onClick="postComment('<?php echo $i ?>')" class="btn btn-sm btn-primary pull-left margin-top" name="comment" value="Comment">
</td>
</tr>
</form>
</table>
</div>
<div align="left" style="margin-bottom:10px;">
<?php
//Getting all the comments corresponding to a particular post
$getComment_cPost = $getPosts_pId;
$getComment->execute();
$getComment->bindColumn("comment_id", $getComment_cId);
$getComment->bindColumn("comment_user", $getComment_cUser);
$getComment->bindColumn("comment_detail", $getComment_cDetail);
while ($getComment->fetch()) {
//Getting only the comments written by a particular user
$uid = $getComment_cUser;
$getUser->execute();
$getUser->bindColumn('user_fname', $cfName);
$getUser->bindColumn('user_lname', $clName);
$getUser->fetch();
?>
<div style="background-color:#f6f7f8;">
<font style="font-size:14px; color:#4c5d98"><b><?php echo "@" . $cfName . " " . $clName ?></b></font>
</div>
<div style="background-color:#f6f7f8;">
<font style="font-size:14px;"><?php echo $getComment_cDetail ?></font>
</div>
<div style="margin-bottom:10px; background-color:#FFF;">
</div>
<?php
}
?>
<div id="rslt">
</div>
</div>
I have created a variable i and am incrementing it accordingly to assign every comment a seperate id otherwise the values won't submit.