how to use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this?

admin

Administrator
Staff member
I'm trying to send my comment form using ajax, right now when user inserts a comment then whole page gets refreshed. I want this to be inserted nicely without page getting refreshed.
So I tried bunch of things but no luck. since I'm a beginner, I tried to follow many tutorial links;
<a href="https://realpython.com/blog/python/django-and-ajax-form-submissions/">https://realpython.com/blog/python/django-and-ajax-form-submissions/</a>
<a href="https://impythonist.wordpress.com/2...ication-practise/comment-page-1/#comment-1631">https://impythonist.wordpress.com/2...ication-practise/comment-page-1/#comment-1631</a>

I realize my problem is that I have a hard time manipulating my code in views.py and forms.py
Thus before doing a client side programming(js and ajax) I need to set my backend(python code) again to be set for the ajax.
Can someone please help me with this?
I don't know how to set my backend....

Code:
  &lt;div class="leave comment&gt;
    &lt;form method="POST" action='{% url "comment_create" %}' id='commentForAjax'&gt;{% csrf_token %}
    &lt;input type='hidden' name='post_id' value='{{ post.id }}'/&gt;
    &lt;input type='hidden' name='origin_path' value='{{ request.get_full_path }}'/&gt;

    {% crispy comment_form comment_form.helper %}
    &lt;/form&gt;
    &lt;/div&gt;



&lt;div class='reply_comment'&gt;
    &lt;form method="POST" action='{% url "comment_create" %}'&gt;{% csrf_token %}
    &lt;input type='hidden' name='post_id' id='post_id' value='{% url "comment_create" %}'/&gt;
    &lt;input type='hidden' name='origin_path' id='origin_path' value='{{ comment.get_origin }}'/&gt;
    &lt;input type='hidden' name='parent_id' id='parent_id' value='{{ comment.id }}' /&gt;
    {% crispy comment_form comment_form.helper %}

    &lt;/form&gt;
    &lt;/div&gt;

    &lt;script&gt;
     $(document).on('submit','.commentForAjax', function(e){
      e.preventDefault();

      $.ajax({
        type:'POST',
        url:'comment/create/',
        data:{
          post_id:$('#post_id').val(),
          origin_path:$('#origin_path').val(),
          parent_id:$('#parent_id').val(),
          csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        success:function(json){

I don't know what to do here...I tried it but failing....what is going on here })


this is my forms.py

Code:
class CommentForm(forms.Form):
    comment = forms.CharField(
        widget=forms.Textarea(attrs={"placeholder": "leave your thoughts"})
    )

    def __init__(self, data=None, files=None, **kwargs):
        super(CommentForm, self).__init__(data, files, kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False
        self.helper.add_input(Submit('submit', 'leave your thoughts', css_class='btn btn-default',))

and my views.py

Code:
def comment_create_view(request):
    if request.method == "POST" and request.user.is_authenticated() and request.is_ajax():
        parent_id = request.POST.get('parent_id')
        post_id = request.POST.get("post_id")
        origin_path = request.POST.get("origin_path")
        try:
            post = Post.objects.get(id=post_id)
        except:
            post = None

        parent_comment = None
        if parent_id is not None:
            try:
                parent_comment = Comment.objects.get(id=parent_id)
            except:
                parent_comment = None

            if parent_comment is not None and parent_comment.post is not None:
                post = parent_comment.post

        form = CommentForm(request.POST)
        if form.is_valid():
            comment_text = form.cleaned_data['comment']
            if parent_comment is not None:
                # parent comments exists
                new_comment = Comment.objects.create_comment(
                    user=MyProfile.objects.get(user=request.user),
                    path=parent_comment.get_origin, 
                    text=comment_text,
                    post = post,
                    parent=parent_comment
                    )
                return HttpResponseRedirect(post.get_absolute_url())
            else:
                new_comment = Comment.objects.create_comment(
                    user=MyProfile.objects.get(user=request.user),
                    path=origin_path, 
                    text=comment_text,
                    post = post
                    )
                return HttpResponseRedirect(post.get_absolute_url())
        else:
            messages.error(request, "There was an error with your comment.")
            return HttpResponseRedirect(origin_path)

    else:
        raise Http404

I'm still very shaky on the idea of using ajax even after reading a tutorial about it...how json comes into play and how I should modify views.py too....can someone please explain how they all group together?and help me getting this done...

Code:
    else:
        raise Http404