Need to press submit twice for submitting a form with ajax (jquery validation plugin)

情到浓时终转凉″ 提交于 2019-12-23 05:42:12

问题


The form is validated before submit with this plugin. And submitted as shown in the code:

jQuery.validator.setDefaults({
   submitHandler: function(){ 
      jQuery("form").submit(function(e) {
          e.preventDefault();
          jQuery.post(base_url + "blog/ajax_comment", { author: jQuery("#author").val(), email: jQuery("#email").val(), url: jQuery("#url").val(), message: jQuery("#message").val() , post_ID: jQuery("#post_ID").val(), not: jQuery("#not").val() }, function (data) {
             //do stuff here
          });
      });
  }
});

jQuery().ready(function() {
   // validate the comment form when it is submitted
   jQuery("#commentform").validate();
});

In order to be submitted, I need to press the submit button twice. I am kind of new to jQuery, and I can't really tell why is that. Is there an easy way to fix this?


回答1:


The submitHandler is already overriding the default event, so just place the code for the ajax submission in there:

jQuery.validator.setDefaults({
  submitHandler: function(){ 
    jQuery.post(base_url + "blog/ajax_comment", { author: jQuery("#author").val(), email: jQuery("#email").val(), url: jQuery("#url").val(), message: jQuery("#message").val() , post_ID: jQuery("#post_ID").val(), not: jQuery("#not").val() }, function (data) {
      //do stuff here
    });
  }
});

If you elements have name attributes that match their IDs though, just use .serialize(), like this:

jQuery.validator.setDefaults({
  submitHandler: function(form){ 
    jQuery.post(base_url + "blog/ajax_comment", jQuery(form).serialize(), function (data) {
      //do stuff here
    });
  }
});

What's happening with your current code is that in the submit handler, it's attaching a new submit handler for next time, rather than actually running your code. Instead, just run your code directly in the submitHandler callback.



来源:https://stackoverflow.com/questions/3846930/need-to-press-submit-twice-for-submitting-a-form-with-ajax-jquery-validation-pl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!