Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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; https://realpython.com/blog/python/django-and-ajax-form-submissions/ https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/comment-page-1/#comment-1631

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....

  <div class="leave comment>
    <form method="POST" action='{% url "comment_create" %}' id='commentForAjax'>{% csrf_token %}
    <input type='hidden' name='post_id' value='{{ post.id }}'/>
    <input type='hidden' name='origin_path' value='{{ request.get_full_path }}'/>

    {% crispy comment_form comment_form.helper %}
    </form>
    </div>



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

    </form>
    </div>

    <script>
     $(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

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

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...

    else:
        raise Http404
like image 780
mike braa Avatar asked Mar 25 '16 09:03

mike braa


1 Answers

see official document of submit() and serialize() and modify your ajax all like this :

<script>
     $('#commentForAjax' ).submit(function(e){
      e.preventDefault();

      $.ajax({
        type:'POST',
        url:'comment/create/',  // make sure , you are calling currect url
        data:$(this).serialize(),
        success:function(json){              
          alert(json.message); 
          if(json.status==200){
             var comment = json.comment;
             var user = json.user;
             /// set `comment` and `user` using jquery to some element
           }             
        },
        error:function(response){
          alert("some error occured. see console for detail");
        }
      });
     });

At backend side you are returning HttpResponseRedirect() which will redirect your ajax call to some url(status code=302). I will suggest to return any json response.

For Django 1.7+ add line from django.http import JsonResponse to return json response

For pre Django 1.7 use return HttpResponse(json.dumps(response_data), content_type="application/json")

Modify this portion of your views.py to return Json response

def comment_create_view(request):
# you are calling this url using post method 
if request.method == "POST" and request.user.is_authenticated():
    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:
        # you should return from here , if post does not exists
        response = {"code":400,"message":"Post does not exists"}
        return HttpResponse(json.dumps(response), content_type="application/json")

    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
                )
            response = {"status":200,"message":"comment_stored",
             "user":new_comment.user, 
             "comment":comment_text,
            }
            return HttpResponse(json.dumps(response), content_type="application/json")
        else:
            new_comment = Comment.objects.create_comment(
                user=MyProfile.objects.get(user=request.user),
                path=origin_path, 
                text=comment_text,
                post = post
                )
            response = {"status":200,"message":"new comment_stored",
             "user":new_comment.user,
             "comment":comment_text,}
            return HttpResponse(json.dumps(response), content_type="application/json")
    else:
        messages.error(request, "There was an error with your comment.")
        response = {"status":400,"message":"There was an error with your comment."}
        return HttpResponse(json.dumps(response), content_type="application/json")

You don't have to use rest-framework. But if you use rest-framework for this purpose , it will be easy to implement.

like image 98
Hiren patel Avatar answered Oct 12 '22 18:10

Hiren patel