2016-09-05 11 views
0

ページを再読み込みせずにdivを更新するために、jquery with railsでJavaScriptを使用しようとしています。その作業はしていますが、コメントは2回作成されています。私は何かが部分的な形で間違っていることを知っていますが、それを理解できませんでした。どんな助け?link_toを送信するフォームが2回あるのはなぜですか?

_new_comment.html.erb

<%= form_for [:home, Comment.new], :url => home_comments_path, :html => {:id => "comment-new-" + post.id.to_s} do |f| %> 

    <div> 
     <%= f.text_area :message, :class => "message-area-" + post.id.to_s, :placeholder => "Add comment..." %> 

     <%= f.hidden_field :post_id, :value => post.id %> 

     <span class="new-comment"><%= link_to 'Add', '#', remote: true, :onclick => "$('#comment-new-#{post.id}').submit()" %></span> 
    </div> 

<% end %> 

comments_controller.rb

def create 
    @comment = Comment.new(comment_params) 
    @comment.user_id = current_user.id 

    if @comment.save 
     flash[:notice] = 'Comment added sucessfully' 
     respond_to do |format| 
      format.html { redirect_to home_posts_url } 
      format.js 
     end 
    end 
end 

create.js.erb

$("#comment-new-83").before('<div class="notice"><%= escape_javascript(flash[:notice]) %></div>'); 
$("#comment-new-83")[0].reset(); 

ホーム -

次のファイルです。 js

jQuery.ajaxSetup({ 
    'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
}) 

$(document).ready(function() { 
    $("#comment-new-83").submit(function() { 
     $.post($(this).attr("action"), $(this).serialize(), null, "script"); 
     return false; 
    }) 
}) 
+0

'リモートを削除します。link_to''からtrue'ををして試してみても ':onclick'。 –

+0

どこでonclickを使用しますか? – Beginner1111

+0

フォームに 'submit'イベントをバインドしているので、どこにでも':onclick'を置く必要はありません。 –

答えて

0

form_forは自動的にコントローラに送信されます。 jqueryを使用してフォームを明示的に送信する必要はありません。

Reference

+0

うん。解決済み。リモートを追加:form_forステートメントにtrueが追加されました。ありがとうございました – Beginner1111

関連する問題