Andreas Lyngstad
Andreas Lyngstad

Reputation: 4927

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?

Upvotes: 1

Views: 928

Answers (1)

Nick Craver
Nick Craver

Reputation: 630637

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.

Upvotes: 1

Related Questions