简体   繁体   中英

Rails 3 Jquery validate plugin

I have this js code

$(".new_milestone").validate({
     submitHandler: function(form) {
    $(form).submitWithAjax();
   },
     errorPlacement: function(error, element) {
        error.insertBefore(element);
     }
   });  

It all works, errorPlacement and the submitWithAjax function. But when I post the form the second time without reloading the page, the form gets posted two times. Next time 3 times and so on.

When I do this

 $(".new_milestone").validate({
             errorPlacement: function(error, element) {
                error.insertBefore(element);
             }
           });
$(".new_milestone").submitWithAjax(); 

It works, but it does the ajax post even if the form is not valid.

The submitWithAjax function looks like this (thanks Ryan Bates)

jQuery.fn.submitWithAjax = function() {
  this.submit(function() { 

    $.post(this.action, $(this).serialize(), null, "script");
    $('.spinning').show(); 
    $("#dialog_form").dialog("close")
    return false;
  })
  return this;
};

Any ideas on stopping this behavior?

This is happening because your ssubmitWithAjax function doesn't * actually* submit (fire the event), it attaches a submit handler for when the submit happens (which the normal behavior is doing)...since you're calling it in a submit situation, just remove the handler wrapper and actually submit, like this:

jQuery.fn.submitWithAjax = function() {
  $.post(this.attr("action"), this.serialize(), null, "script");
  $('.spinning').show(); 
  $("#dialog_form").dialog("close")
  return false;
};

Note the .attr("action") change, because this is not a jQuery object, not a <form> DOM element since it's directly in the plugin.


Previously, you were attaching an additional submit handler each time, which is why you get 1, 2, 3.... submits, by just calling the submit code you want, this won't happen, since inside submitHandler is the valid place to go ahead and submit anyway.

As an aside, the callback function to $.post() is optional, so you can leave off that null, and it'll function properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM