最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery call custom form submit, then normal - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 6

Try 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;
    }
});
发布评论

评论列表(0)

  1. 暂无评论