admin管理员组文章数量:1313347
I want to attach a submit() handler to a form to run an ajax request, and when that es back, the form submits itself normally. Is this possible? $('#myForm').submit() will just recursively call the same function.
I'd rather not attach the event handler to the click of the submit button, because not all users submit forms with the mouse. Many, like myself, just use the return key.
I want to attach a submit() handler to a form to run an ajax request, and when that es back, the form submits itself normally. Is this possible? $('#myForm').submit() will just recursively call the same function.
I'd rather not attach the event handler to the click of the submit button, because not all users submit forms with the mouse. Many, like myself, just use the return key.
Share Improve this question edited Nov 21, 2011 at 15:32 Reporter 3,9485 gold badges35 silver badges49 bronze badges asked Nov 21, 2011 at 15:30 UncleCheeseUncleCheese 1,5849 silver badges14 bronze badges3 Answers
Reset to default 6Try this. In the below code I am unbinding the form submit event handler in ajax success handler and then submitting the form.
$('form').bind('submit', function(){
//Do ajax call here
$.ajax({
url: "url",
success: function(){
//On success do what you want to do
//and then ubind the submit event handler and submit the form
$('form').unbind('submit').submit();
}
});
//Prevent default form submit
return false;
});
This should work for you:
$('form').submit(function(e) {
e.preventDefault();
var that = this;
$.post('url', function() {
that.submit();
});
});
e.preventDefault()
stops the default form submit. Then you can call .submit()
on the dom element to perform a submit which is not caught by the jQuery handler.
You could have a variable that flags whether the ajax response has been received or not. This may be a little less graceful than unbinding the 'submit' event handler, but it's another idea.
var ajaxResponse = false;
$('form').submit(function() {
var form = $(this);
if( ajaxResponse == false ){
$.post('url', function() {
ajaxResponse = true;
// Do something
form.submit();
});
return false;
}else{
return true;
}
});
本文标签: javascriptjquery call custom form submitthen normalStack Overflow
版权声明:本文标题:javascript - jquery call custom form submit, then normal - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741934663a2405781.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论