开发者

Unobtrusive jQuery and Rails with AJAX and form validation

I am looking for a way to call successfully custom function from submitHandler to do proper ajax post.

Here is my custom function:

jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};

Before using validate plugin I had following which worked fine:

$(document).ready(function() { $("#my_form").submitWithAjax(); }

Now I have added the validation part and have no idea how to call my开发者_运维知识库 custom submitWithAjax function??

$(document).ready(function() {

$("#my_form").validate({

/*Validations - works perfectly!! */

},

submitHandler: function(form) {

/* $("#my_form").submitWithAjax(); - this works but
introduces recursion */

/* how to call custom subitWithAjax() ????? */

}

});
})

Thanks!


Your custom plugin only adds a submit event handler which won't work with the validator plugin try this

$("#my_form").validate({
    /*Validations - works perfectly!! */
},
submitHandler: function(form){
    $.post(this.action, $(form).serialize(), null, "script");
});


Hope you found your answer, bogumbiker. I ended up including rails.js from the jquery-ujs library:

http://github.com/rails/jquery-ujs/blob/master/src/rails.js

and calling the callRemote() function instead of submitWithAjax() after validation. Worked for me in Rails 3.


I was having the same problem using rails.js, so I decided to call the validation within the ajax:beforeSend callback (described here). Here is the workaround:

$('form').live('ajax:beforeSend', function(event, xhr, status){
  var form = $(this);
  form.validate({
    /* validation options go here */
  });
  if (!form.valid()) {
    return false;
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜