1

I have code set up so that users can delete comments on an article. However currently, when they delete the comment it will refresh the page and take them back to the top. I'm trying to implement Ajax so that when they delete the comment it'll do it without a page refresh.

This is the code I have currently for deleting a comment.

index.py

<form action="{% url 'add-delete-view' %}" method="POST" class="ui form">
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{c.id}}">
<button type="submit" onClick="deleteComment({{c.id}})" id= "{{c.id}}" class="ui primary button c_edit{{c.id}}" name="submit_d_form">delete</button>

urls.py

path('deleteComment/', views.delete_comment, name='add-delete-view')

views.py

@login_required
def delete_comment(request):
    comment_obj = Comment.objects.get(id=request.POST.get('comment_id'))
    comment_obj.delete()

    return redirect('index')

I've attempted to try and implement Ajax but I'm just feeling hopeless in trying to get it work.

In index.py I've added function:

function deleteComment(comment_id) {
    var action = confirm("Are you sure you want to delete this comment?");
    var comment = $(this)
    if (action != false) {
        $.ajax({
            method: 'DELETE',
            url: '{% url "add-delete-view" %}',
            success: function (data, textStatus, jqXHR) {
                    comment.remove();
            },
    });
  }
}

But I'm just not sure where to go next or if this will even work. Any help or code would be greatly appreciated. It feels like this simple concept is very tough to get working.

Thanks in advance.

Hassan
  • 39
  • 6
  • Hi , check [this](https://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit) post will help you. – Swati Dec 04 '20 at 05:42

0 Answers0