I would like to add commenting functionality to my posts.
I can add the comment once and the partial is rendered without a reload, but when I add another comment it only renders the partial (nothing else)
Here is the create method I am calling:
def create
@comment = Comment.new(params[:comment])
@snippet = @comment.snippet
@comment.save
@comment = Comment.new
render :partial => "snippets/comment"
end
Javascript:
$(document).ready( function(){
save_comment();
});
function save_comment() {
$("#new_comment").submit(function (e) {
e.preventDefault();
var url = "/comments/create";
var post_data = $('#new_comment').serialize();
logger(post_data);
post_data = add_auth_token(post_data); // add authenticity token to post for forgery protection (works fine)
$.post(url,
post_data,
function(data) {
$("#comments_container").html(data);
$("#comment_value").val("");
});
});
}
And the form
<%= form_for(@comment) do |f| %>
<%= f.text_field :value %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :snippet_id, :value => @snippet.id %>
<div class="actions">
<%= f.submit "Post" %>
</div>
<% end %>
Since the html is being added after the event listener code is executed it is not able to attach an event handler for
submitfor elements added later in the DOM. You need to make use of the on api to bind the events and it will attach a delegated event handler that can process events from descendant elements that are added to the document at a later time.In your case you need to change your code to: