A
A
Artem Rassadin2021-08-14 23:07:07
AJAX
Artem Rassadin, 2021-08-14 23:07:07

Why does a page flip to another page after submitting a form via ajax request in django?

Good evening, I need to save a comment from the user to the database and then do the necessary operations. To do this, I pass the form data via ajax to django, validate it, save it, and pass the information about successful processing back. But after all this, the page is redirected to the link in which I processed the form. Here is the code:

JavaScript

forms = document.querySelectorAll('#form-modal')

  forms.forEach(form => {
    $(form).submit(function() { // On form submit event
      $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        method: "POST", // GET or POST
        dataType: 'json',
        url: $(this).attr('action'), // the file to call ( video/form )
        success: function(data) { // on success.. ( этот код не выполняется из-за переброса страницы )
          console.log(true)
        }
      })
    });
    return false;
  })


views.py

def formVideo(request):
    if (request.method == 'POST') and (request.is_ajax()):
        form = addComment(request.POST)
        if form.is_valid():
            form.save()
    
    return HttpResponse('ok')


PS The comments are saved, but the subsequent ajax code - the request is not executed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Spartak (Web-StyleStudio), 2021-08-15
@Spartak-2205

https://developer.mozilla.org/en/docs/Web/API/Even...

$(form).submit(function(event) {
  event.preventDefault();
  // далее ваш код 
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question