views:

41

answers:

1

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  A: 

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.

Nick Craver
+1 Works great! Thanks (for the tip also)
Zack