i have been battling with this piece of code for hours without any headway. Can anyone assist me in getting around this please? I’m working on a forum page on my website, with comments and replies to comments functionalities. On click of the Reply button under each comments, a textarea dynamically shows up for reply. The replies are inserted to the database with a reply id and the original comment id (the id generated while posting the original comment been replied to). My challenge now is that replies to any of the comments on the forum seem to reference only the id of the latest comment (perhaps because the reply forms are dynamically generated). Thus in my database, they are having an Id of the latest comment. This in effect means on fetching, the replies will all queue up under the latest comment.What i need is a way of referencing the id of the comment been replied to. Here’s my php code:
<?php
require("includes/conn.php");
$stmt=$conn->prepare("SELECT post_id, user, topic, post, time FROM post_tb ORDER BY time DESC");
$stmt->execute();
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
if ($num_of_rows > 0){
while ($row = $result->fetch_assoc()){
$post_id = $row['post_id'];
$user = $row['user'];
$topic = $row['topic'];
$post = $row['post'];
$time = $row['time'];
$time = date('M dS, Y g:i A', strtotime($time));
echo '<div>
<div>
<h5><strong>'.$user.'</strong></h5><h6>'.$time.'</h6>
<h5><strong>'.ucfirst($topic).'</strong></h5>
<p data-id="'.$post_id.'">'.$post.'</p>
</div>
<div>
<button type="button" class="btn btn-primary rep" id="but_rep" data-id="'.$post_id.'">Reply</button>
</div>
<form id="comment_reply" data-id="'.$post_id.'" method="post" action="">
<input type="text" class="hidden" value="'.$post_id.'" id="post_id">
<input type="text" class="hidden" value="'.$user.'" id="user">
<textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
<button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
</form>
<div/>';
}
}
?>
And my Ajax/jquery here:
$("form#comment_reply").hide();//Comment reply form hidden at page load
//To hide reply button and show the reply form
$(document).on('click', 'button.rep', function(e){
e.preventDefault();
var closestDiv = $(this).closest('div');
var closestForm = $(closestDiv).next('form#comment_reply');
$(closestDiv).fadeOut();
$(closestForm).fadeIn();
});
//To process comment reply
$(document).on("click", "form button#post_rep_sub", function(e){
e.preventDefault();
var reply = $("form textarea#post_rep").val();
var name = $("input#user").val();
var post_id = $("input#post_id").val();
if (reply != ''){
$.post('insert_post_reply.php', {'reply':reply, 'name':name, 'post_id':post_id}, function(data){
if (data = 'yes'){
$("form textarea#post_rep").val("");
fetchCommentReply();
}
});
}else{
return false;
}
});