Answer the question
In order to leave comments, you need to log in
How to correctly submit a form after one or another response with Ajax?
Hello!
The task is to submit the form when clicking on the button (redirect the page, etc.), but only after ajax returns the data.
Here is a piece of code with comments:
$button.on( 'click', function(e) {
e.preventDefault(); // предотвращаем сабмит, т.к. данные еще не получены
$.ajax( {
url : '/someUrl',
type : 'POST',
dataType : 'json',
data : data,
success : function( data ) {
if ( data.status == 'SUCCESS' ) { // тут получили данные
return true; // а тут я пытаюсь сабмитить форму
}
}
} );
} );
Answer the question
In order to leave comments, you need to log in
$button.on( 'click', function(e) {
$.ajax( {
url : '/someUrl',
type : 'POST',
dataType : 'json',
data : data,
success : function( data ) {
if ( data.status == 'SUCCESS' ) { // тут получили данные
$(this).closest('form').submit();
}
}
} );
return false;
} );
DO NOT handle submission like this!
The user has every right not to click your button with the mouse, but to transfer focus to it with a tab and press enter. In this case, your handler simply won't work.
$form.on( 'submit', function(e) {
e.preventDefault();
location.href = 'http://yandex.ru';
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question