Очень давно я знаю, что действие перенаправления по умолчанию Form
не будет ждать, пока ajax вернет свой результат. Таким образом, вы можете использовать логическую переменную для управления этим .. см. Следующий код
$(document).ready(function(){
var DefaultFormAction = false; //set the default form action to false
$('form').on('submit' , function(e){
var $this = $(this);
if(DefaultFormAction == false){ // when the default action is false
e.preventDefault(); // prevent the default redirect
setTimeout(function(){ // I use setTimeout here for testing .. Use the next code in your ajax success
DefaultFormAction = true; // return default action to true
$this.submit(); // then submit the form again
} ,10000);
console.log('This result when default is false you will go to the default form action after 10second');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
</form>
Для проверки действие перенаправления Form
по умолчанию не будет ждать, пока ajax вернет свой результат вы можете использовать e.preventDefault()
внутри setTimeout
и даже если вы сделаете время 1
мс без $this.submit()
, оно все равно будет использовать перенаправление по умолчанию
$(document).ready(function(){
var DefaultFormAction = false; //set the default form action to false
$('form').on('submit' , function(e){
var $this = $(this);
if(DefaultFormAction == false){ // when the default action is false
setTimeout(function(){ // I use setTimeout here for testing .. Use the next code in your ajax success
e.preventDefault(); // prevent the default redirect
} , 1);
console.log('This result when default is false you will go to the default form action after 10second');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
</form>