John
John

Reputation: 13735

Using jQuery Form Plugin with Rails, works on first comment post but not after

I'm using JQuery Form Plugin as follows:

$('document').ready( ->
  options = 
    beforeSubmit: markComment
  $('.comment_form').ajaxForm(options)
)

markComment = (arr, $form, options) ->
  $form.closest('.comment_area').addClass('add_comment_here')

When the comment gets created the following javascript gets called server side:

$('.add_comment_here').html("<%= escape_javascript(render(:partial =>'activities/comments', :locals => {:activity => @activity})) %>")
$('.add_comment_here').removeClass('add_comment_here')
$('.add_comments_box').fadeOut()

A comment post works fine the first time, but on the second attempt I get 'Template is missing' as if the form was being submitted before the AJAX method got to be called. How do I get it work the same for multiple comments?

This is the form_tag in haml:

=form_tag({ :action => 'create', :controller => 'comments' }, { :class => 'comment_form'}) do

Upvotes: 0

Views: 85

Answers (1)

Ryan
Ryan

Reputation: 1811

Judging by the comments above, I'm not sure this answer is needed. If you still want to re-render your form, then you just need to make sure to re-ajax the new element once it's been added to the page. Just add that $('.comment_form').ajaxForm(options) into the JS that gets run after the re-render.

What I believe is happening is that your response ends up removing the previous form from the document and then adds a new one. When this happens, any JS that might have been "attached" to that previous form element is removed along with the element. If your response creates a brand new form element, you have to make sure to apply any special JS additions to the brand new element.

Also be sure to re-define the options in your response JS, since the previous options declaration will have fallen out of scope. You may just be able to put the options+ajaxing into a separate function called something like function ajaxify_forms and just call that function on document ready and then also whenever you replace the form element.

Upvotes: 2

Related Questions