Answer the question
In order to leave comments, you need to log in
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;
})
def formVideo(request):
if (request.method == 'POST') and (request.is_ajax()):
form = addComment(request.POST)
if form.is_valid():
form.save()
return HttpResponse('ok')
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question