Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

How do I display the new comment in the comments section when added and still keep the submission ajax code?

Immortal2004

New Coder
My code is below:
Code:
 $commentsQuery = "SELECT username, created_at, content FROM comments WHERE post_id ={$row['id']}  ORDER BY created_at DESC";
$commentsResult = mysqli_query($con, $commentsQuery);
$commentsCount = $commentsResult->num_rows;
if ($commentsCount > 0) {
  echo "<details>
    <summary><p style='font-size:12px; cursor:pointer; text-align:left; margin-left:10px; margin-top:17px; font-weight:600; margin-bottom:0px; color:white'><img src='comment.svg' style='width:16px; filter:invert(1); margin-bottom:-3px'> Comments ({$commentsCount})</p></summary>
    <br>
<div class='comments-section' style='max-height:270px; overflow-y:auto; overflow-x:hidden' id='comments_{$row['id']}'><h2 class='sr-only'><img src='comment.svg' style='filter:invert(1); width:16px; margin-bottom:-3px'> Comments</h2>";
  while($comment = mysqli_fetch_assoc($commentsResult)) {
    echo "<div role='article' class='comment-card' style='margin:10px; border-radius:7px'>
      <p style='font-weight:600; margin-bottom:-8.5px; margin-left:10px; margin-top:3px'><a href='profile?username=".$comment['username']."' title='Click to view ".$comment['username']."' style='font-weight:600; font-size:12px'>".$comment['username']."</a><span style='font-weight:700; float:right; background-image:linear-gradient(127deg, #00beff, #00aeff, #0083ff); margin-top:-4px; color:white; padding:2px 7px; border-radius:50px; margin-right:4px; font-size:12px'>{$comment['created_at']}</span></p>
      <p class='comment-content' style='background-color:white; border-radius:7px; margin-left:10px; margin-right:10px; font-weight:400; font-size:12px; padding:6px 10px; border:none'>{$comment['content']}</p>
<script>
function addComment(postId) {
    $.ajax({
        url: 'add_comment.php',
        type: 'POST',
        data: {
            title: $('input[name="title"]').val(),
            postId: postId,
            username: $('#username').val(),
            comment: $('#comment-' + postId).val()
        },
        success: function(data) {
            console.log("Got " + data.status);
        },
        error: function() {
            console.log('error');
        }
    });
    return false;
}
</script>
 
To dynamically display the new comment when added and keep the AJAX submission code, you can modify your success callback function in the AJAX request. After the comment is successfully added to the database, you can append the new comment HTML to the comments section. Here's an example of how you can achieve this:
  1. Update your addComment function in the script:

JavaScript:
<script>
function addComment(postId) {
$.ajax({
url: 'add_comment.php',
type: 'POST',
data: {
title: $('input[name="title"]').val(),
postId: postId,
username: $('#username').val(),
comment: $('#comment-' + postId).val()
},
success: function(data) {
if (data.status === 'success') {
// Append the new comment to the comments section
var newCommentHTML = `
<div role='article' class='comment-card' style='margin:10px; border-radius:7px'>
<p style='font-weight:600; margin-bottom:-8.5px; margin-left:10px; margin-top:3px'>
<a href='profile?username=${data.comment.username}' title='Click to view ${data.comment.username}' style='font-weight:600; font-size:12px'>${data.comment.username}</a>
<span style='font-weight:700; float:right; background-image:linear-gradient(127deg, #00beff, #00aeff, #0083ff); margin-top:-4px; color:white; padding:2px 7px; border-radius:50px; margin-right:4px; font-size:12px'>${data.comment.created_at}</span>
</p>
<p class='comment-content' style='background-color:white; border-radius:7px; margin-left:10px; margin-right:10px; font-weight:400; font-size:12px; padding:6px 10px; border:none'>${data.comment.content}</p>
</div>
`;
$('#comments_' + postId).prepend(newCommentHTML);
}
console.log("Got " + data.status);
},
error: function() {
console.log('error');
}
});
return false;
}
</script>
In this modified script:
  • The success callback checks if the status returned from the server is 'success'.
  • If successful, it creates the HTML for the new comment using the data returned from the server (data.comment).
  • It then prepends the new comment HTML to the comments section using $('#comments_' + postId).prepend(newCommentHTML);.
Make sure that your add_comment.php script returns the relevant information (e.g., the new comment details) in the response to populate the new comment in the comments section. Adjust the PHP script accordingly.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom