Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use jQuery Form Plugin with Rails js.erb template?
    text
    copied!<p>I am using the jQuery Form Plugin with my Rails app. I have a form like this:</p> <pre><code>&lt;form action="/comments" id="comment_form" method="post"&gt; &lt;textarea cols="60" id="comment_comment" name="comment[comment]" rows="3"&gt;&lt;/textarea&gt; &lt;input id="comment_submit" name="commit" type="submit" value="Add comment" /&gt; &lt;/form&gt; </code></pre> <p>My application.js file has:</p> <pre><code>jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }); $(document).ready(function(){ $("#comment_form").ajaxForm(); }); </code></pre> <p>My Comments controller is like this:</p> <pre><code>def create @comment = Comment.new(params[:comment]) respond_to do |wants| if @comment.save flash[:notice] = 'Added comment.' wants.js end end end </code></pre> <p>And I have some jquery code in /views/comments/create.js.erb like:</p> <pre><code>$("#comment_form).hide(); </code></pre> <p>and some other stuff.</p> <p>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)</p> <pre><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(); }); </code></pre> <p>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:</p> <pre><code>$("#comment_form").ajaxForm({success: function(){$("comment_form").hide()}}); </code></pre> <p>then that jQuery code works. But I need to run the erb template (because I do things like render a partial inside). </p> <p>Thanks for any insights.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload