EbrahemSamer
4 months ago

Why Ajax calls one time?

Posted 4 months ago by EbrahemSamer

I've comments in blog and every comment has delete button to delete the comment,

I wanna delete it using ajax without refreshing the page.

so I've made ajax call when the form submitted and it works but for one comment and the another comment the page is refreshed.

// the ajax call

$("#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>

// delete function

public function destroyComment(Request $request) {

    $comment = Comment::findOrFail($request->comment_id);
    if($comment) {
        $comment->delete();
        $success = $comment->id;
    }
    return response()->json(['success' => $success], 200);
}

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