EbrahemSamer
4 months ago

Why ajax calls do not execute on appended html?

Posted 4 months ago by EbrahemSamer

I've comments system, I want user to add comments and delete its own without refreshing the page and it works fine but when user add comment using ajax and delete the same added comment it deleted but after page refreshed.

javascript

$(".deletecomment").on("submit", function(e) { e.preventDefault();

    let slug = $(".deletecomment input[name='slug']").val();
    let data = $(this).serialize();
    $.ajax({
        url: '/blog/post/'+slug,
        method: "Delete",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: data,
        dataType: 'json',
        success: function(data) {
            $(".comment"+data.success).remove();
        },

    });
});

HTML

@csrf @method('DELETE')
                                    <a data-target="#updatecomment" data-toggle="modal" href="" class="btn btn-secondary btn-sm">Edit</a>
                                    @if($comment->comment_type == 'comment')
                                    <a href="" class="btn btn-info btn-sm">Reply</a>
                                    @endif

                                    <input type="hidden" name="comment_id" value="{{ $comment->id }}">
                                    <input type="hidden" name="slug" value="{{ $comment->post->slug }}">
                                    <input onclick="return confirm('Are you sure?');" type="submit" value="Delete" class="btn btn-danger btn-sm" />
                                </form>

Please sign in or create an account to participate in this conversation.