So I am just making a little blog project with codeigniter. What I am trying to do is once a comment is added, I want to be able to delete it. Deleting comments works for older comments, but not for the newer ones added. In order for them to be deleted the page has to be refreshed. I have looked through some answers on stackoverflow already but none seem to be my problem. The problem is when I click remove on my new comment, its not registering that I have even clicked the element. If you look below I added a console.log test which should show up when I click the element, but nothing happens. How would I fix this?
EDIT: I noticed something in the console (Using firefox). Near to the remove element there is a black little box with "ev" written in it. It comes up next to the other comments but not the new comment.
EDIT: Ok I should have done a little more digging, I found the answer:
Change
$(".com-delete").click(function()
TO
$(document).on("click",".com-delete",function()
Code:
<script>
$(document).ready(function(){
$("#comment").submit(function(event){
event.preventDefault();
var body = $("textarea#body").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "comments/add_comment/" + "<?php echo $post['id']; ?>",
dataType: "json",
data: {"body":body},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
console.log(status);
}
else {
var html = "<div class='well'><h5>"+body+"</h5><p><em>By:<strong><?php echo $this->session->userdata('username'); ?></strong></em><span class='com-delete' id='"+xhr.responseText+"' >remove</span></p></div>";
$("#comment").after(html);
$("#body").val("");
$("#nocomments").html("");
}
}
});
});
$(".com-delete").click(function(){
//WORKS WITH OLD COMMENTS BUT NOT WITH NEW COMMENTS
console.log("test");
var el = $(this);
var com_id=el.attr('id');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "comments/delete_comment/"+com_id,
success: function () {
el.closest("div").remove();
}
});
});
});
</script>