Reputation: 8085
i have a comment system which appends the newly posted comment to the rest. When the user hovers the comment a 'delete' button is shown.
When the user clicks the delete button, a confirm dialog is shown and if confirmed, it will complete an ajax call to remove the comment.
This works perfectly fine for comments that are already on the page, however the Ajax call doesnt seem to work on the appended items.
So an example comment looks like so:
<div class='textcomment' id='".$commentID."'>
<a class='$rightscommentcolor'>USERNAME:</a>
THIS IS THE COMMENT TEXT
<div class='commentActionButton'>
<form action='process/deletecomment.php' method='post' class='delrepcomment'>
<input class='deletecommentsubmit' name='submit-delete' type='$buttontype' value='delete'>
</form>
</div>
</div>
To show the button i use this:
$(".commentsholder").on("mouseenter", ".textcomment", function(){
var $this = $(this);
$(this).closest('.textcomment').find('.commentActionButton').show();
});
And then the delete comment ajax:
$(document).on('submit','.delrepcomment',function(){
var $targetComment = $(this);
if (confirm('Do you really want to delete this comment?')) {
$.ajax({
type: "POST",
url: "process/deletecomment.php",
data: $targetComment.serialize(),
dataType: "json",
success: function(response){
if (response.commentDeleted === true) {
$("#"+response.commentID).remove();
}
else {
$('.delrepcomment').after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
} else {
return false;
}
});
});
This all works okay, however when clicking the delete button on an appended comment the confirm dialog is shown but the comment is not deleted.
Which leads me to believe the ajax call isn't happening?
If i remove the ajax side of things and keep the form directly using the php page it works. Even on the appended comments, but it just doesnt work when the ajax is used.
The comment is appended like so:
if (response.commentSuccess === true) {
$this.closest('.addcomment').prev().append("<div class='textcomment'><a class='"+response.userRights+"'>"+response.username+":</a> "+response.commentToPost+"<div class='commentActionButton'><form action='process/deletecomment.php' method='post' class='delrepcomment'><input class='deletecommentsubmit' name='submit-delete' type='submit' value='delete'></form></div></div>");
}
Upvotes: 0
Views: 226
Reputation: 18292
When you append a new comment via AJAX, you aren't setting the id
attribute of the textcomment
div, so when you get back from the AJAX call, you are unable to locate it by id and remove it:
//DIV does not have id!
...append("<div class='textcomment'><a class='"+r...
Upvotes: 1