1

I followed a solution on how to get Django comment form to submit without page reloading and jumping to the top of the page. I tried many solutions online and offline but still no solution.

The form works correctly, the only problem is the page reload on submit.

I am new to Django Backend and Ajax, I will be happy if someone can help on how to deal with this. Thanks in Advance.

JS AJAX

$( document ).ready(function() {
           
    $(`.comment-form${post_id}`).submit(function() {
          $.ajax({
              data: $(this).serialize(), 
              type: $(this).attr('method'), 
              url: $(this).attr('action'), 
              success: function(response) {
                  $();
              },
              error: function(response) {
                console.log('error', response)
             }
          });
          return false;
    });
});
models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
from django.db import models

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField(max_length=300)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)
VIEWS

from django.shortcuts import render, redirect
from .models import Post, Like
from django.contrib.auth.models import User
from .forms import CommentModelForm
from django.http import JsonResponse

# Create your views here.

def post_comment_create_and_list_view(request):
    qs = Post.objects.all()
    user = User.objects.get(pk=request.user.pk)


    #Comment form
    c_form = CommentModelForm()
        
    if 'submit_c_form' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = user
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    
    context = {
    'qs': qs,
    'user':user,
    'c_form':c_form,
    }

    return render(request, 'posts/main.html', context)
HTML

<form action="" method="POST" class="comment-form" id='{{obj.id}}'>
{% csrf_token %}
  <div class="input-group">
    <input type="hidden" name="post_id" value={{obj.id}}> 
    
    {{ c_form }}
    <div class="input-group-append">
      <button type="submit" name="submit_c_form" class="btn btn-md u-btn-white g-color-red g-text-underline-hover g-brd-gray-light-v3 g-brd-none g-brd-top">Post</button>
      </div> 
    </div>
</form>
MoAlanteh
  • 23
  • 5
  • Can you share the comment model code? Also does this help you in any ways [django-js-how-to-post-a-form-without-reloading-whole-page](https://stackoverflow.com/questions/65052844/django-js-how-to-post-a-form-without-reloading-whole-page/65057658) ? – Ajay Lingayat Nov 30 '20 at 17:31
  • It will be helpful if you specify what works and what does not work – ha-neul Nov 30 '20 at 18:03
  • @AjayLingayat i added the model code now. Thanks for the link, will check it out. – MoAlanteh Nov 30 '20 at 18:13
  • @ha-neul Everything works perfectly, the only problem is the page reloads when i submit a comment and i want to prevent this from happening. – MoAlanteh Nov 30 '20 at 18:16
  • @MoAlanteh see my answer. – Hisham___Pak Nov 30 '20 at 18:24
  • Are you seeing any error in browser console ? Also update your question with changes you made in your code. – Swati Dec 01 '20 at 14:00
  • @Swati the thing is I was following that JS/AJAX example to see if it will prevent the page reload/jumping to the top of the page. Without the JS & AJAX, the comment section is working fine, I can post comments, etc .... the only problem is the page reloads when i send a comment and jumps to the top of the page and i have no idea how to prevent this and have the comments sent without page reloads. – MoAlanteh Dec 01 '20 at 14:53
  • Try suggestion from this [post](https://stackoverflow.com/questions/26567486/prevent-page-reload-and-redirect-on-form-submit-ajax-jquery/43374240) then let know if that still doesn't work. – Swati Dec 01 '20 at 14:57
  • @Swati the suggestion from this post only prevent the default but nothing really happens after that, i think i don’t know how to execute the functions of the success call ( success: function(response) { $(............Missing methods.......) ;) }, The example from the Like & Unlike button should work if implemented correctly. I just don’t know how :( – MoAlanteh Dec 01 '20 at 15:11
  • What do you need to do inside success function ? Also what does `response` has in it ? – Swati Dec 02 '20 at 04:05
  • Greetings @Swati What I need inside success is comment/posting done ✅ . My goal is to be able to submit posts/comments without the page reloads. So anything that can go inside or outside the success function to produce that result is all I want. I really don't have JS or Ajax deep knowledge, I am still new and learning and trying to put things together. The tutorial I followed to create this form doesn’t provide a solution to prevent the comment form from reloading on submit so was trying here and there and got stuck. – MoAlanteh Dec 02 '20 at 16:09
  • So, comments are posted successfully to backend or not ? Also, just use some div and show your text `successful` inside that i.e : `$(".yourdivclassname").text("Successfull");` write this inside success fn. – Swati Dec 03 '20 at 03:55
  • @Swati Yes the comments are posted successfully to the backend and also from the frontend the only problem is the page reloads when after you hit the submit button. Okay will try your suggestion and see. Thx – MoAlanteh Dec 03 '20 at 11:29

1 Answers1

0

You prevent page reload by adding e.preventDefault();

$(`.comment-form${post_id}`).submit(function(e) { // Note here too, on submit a function in created where we catch e
      e.preventDefault(); // Here it is e is an event which is passed on clicking button
      $.ajax({
          data: $(this).serialize(), 
          type: $(this).attr('method'), 
          url: $(this).attr('action'), 
          success: function(response) {
              $();
          },
          error: function(response) {
            console.log('error', response)
         }
      });
      return false;
    });
Hisham___Pak
  • 1,472
  • 1
  • 11
  • 23