I am using the jQuery Form Plugin with my Rails app. I have a form like this:
<form action="/comments" id="comment_form" method="post">
<textarea cols="60" id="comment_comment" name="comment[comment]" rows="3"></textarea>
<input id="comment_submit" name="commit" type="submit" value="Add comment" />
</form>
My application.js file has:
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
$(document).ready(function(){
$("#comment_form").ajaxForm();
});
My Comments controller is like this:
def create
@comment = Comment.new(params[:comment])
respond_to do |wants|
if @comment.save
flash[:notice] = 'Added comment.'
wants.js
end
end
end
And I have some jquery code in /views/comments/create.js.erb like:
$("#comment_form).hide();
and some other stuff.
My problem is the jQuery code inside create.js.erb never happens (i.e. the form doesn't get hidden). If I use this in application.js instead (thanks to Railscast for this code)
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
$(document).ready(function(){
$("#comment_form").submitWithAjax();
});
it all works fine. All the code in create.js.erb works great! I'd rather use the jQuery Form plugin, but I don't understand how to make create.js.erb code run. If do something like:
$("#comment_form").ajaxForm({success: function(){$("comment_form").hide()}});
then that jQuery code works. But I need to run the erb template (because I do things like render a partial inside).
Thanks for any insights.