Yax Yax - 6 months ago 25
HTML Question

Appending jQuery AJAX response to an existing DIV

This the HTML code that displays the first two comments in my site. I want if a user clicks on the

Load more comments
button, it should load the fetched comments that is returned via the jQuery AJAX and append it to the two
divs
in
.comment_data
div but it is not working even though the AJAX seems to be returning the expected result.

This is the HTML code:

<div class = 'feeds'>
<div class = 'comments'>
<div class = 'comment_data>
<div class = 'per_comment'>
<p> slideToggle!</p>
</div>
<div class = 'per_comment'>
<p> classToggle!</p>
</div>
<button class='morecomments' value='7' name = 'more' type='submit'>
Load more comments</button>
</div>
</div>
</div>


And this is the AJAX code:

$(".morecomments").click(function () {
var post_id = $(this).val();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id },
dataType: "html"
});
request.done(function( msg ) {
$(this).prev('.per_comment').html( msg );
});
});


And the comments.php code:

if(isset($_POST['post']) )
{
$post_id = $_POST['post'];
$qry = "SELECT user_id, comment FROM comments WHERE post_id = ? ORDER BY time DESC LIMIT 1, 1000";
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $post_id);
$q->execute();
if($commentz = $q->fetchAll()){
foreach ($commentz as $comment){
echo "<div class = 'per_comment'>";
echo "<p>". $comment[0] ." ". $comment[1] . "</p>";
echo "</div>";
}
}
}

Answer

Try the following:

$(".morecomments").click(function () {

   var $this = $(this);    

   var post_id = $(this).val();
   var request = $.ajax({
     url: "comments.php",
     type: "POST",
     data: { post : post_id },
     dataType: "html"
  });
 request.done(function( msg ) {
     $this.prev('.per_comment').html( msg ); 
  });

});