views:

358

answers:

2

Hello, 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!

A: 

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");
});
PetersenDidIt
That is true but I am also doing jQuery and ajax setup before each ajax request: jQuery.ajaxSetup({ 'beforeSend': function(xhr{xhr.setRequestHeader("Accept", "text/javascript")} });with your suggestion the 'before send' will not be called.
bogumbiker
@bogumbiker The beforeSend event gets triggered by the $.post method your are calling not by the submit event. Your beforeSend function will still work.
PetersenDidIt
@petersendidit - I think you are correct, however the server side code (ror) does not handle the request properly anymore. The authenticity_token is missing. Thanks!
bogumbiker
A: 

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.

@jonphillips - thanks a lot for this. I just started new project in rails 3 and will give it a try. Cheers
bogumbiker