I am working on social site. On first load, it fetches all the post, each with two comment max. If the comments are more than two
it attach More comment
button to it, if clicked, it displays all the comments and replace the button with Less comment
.
That is just a little story of how it works. I want whenever a comment is made, it should be appended to existing ones and displayed instantly via AJAX. It does this but it redisplay each comments 3 times, when you reload the page, everything is okay...
<div class = 'post_updates'>
<div class = 'feeds'>
<div class = 'commentdiv'>
<textarea autocomplete = 'off' class='commenttext form-control' rows = '1'
placeholder='Have your say...'></textarea>
<button class='comment btn btn-xs btn-primary onespacedown' value = '7'
type='submit'>Comment</button>
</div>
</div>
</div>
The jQuery AJAX code:
$('.feeds').on('click', '.comment', function () {
var $this = $(this);
var post_comment = $this.parents('.feeds').find('.commenttext').val();
var post_id = $(this).val();
var user_id = $(".user_id").text();
var request = $.ajax({
url: "insert.php",
type: "POST",
data: { post : post_id , user : user_id, comment: post_comment },
dataType: "html"
});
request.done(function( msg ) {
$pc = $this.parents('.feeds').find('.per_comment');
//fetch comments and display
var request = $.ajax({
url: "comments.php",
type: "POST",
data: {
post: post_id,
user: user_id
},
dataType: "html"
});
request.done(function (msg) {
$pc.html(msg).data('loaded', true);
$this.replaceWith("<button class='lesscomments btn-block pullcomments' value='' name = 'more' type='submit'>Less comments</button>");
$this.parents('.feeds').find('.commenttext').val('');
});
});
})
In advance, thanks.