Rails 5, simple javascript with form submit

时间:2018-03-25 21:02:25

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-5

I am hoping someone can help me here. Been at this for a few hours, but can't seem to figure out why my Javascript is not working on my simple form. I'm simply trying to display comments using the ajax call. I have gem 'jquery-rails', and required jquery, and jquery_ujs in my application.js file. Here's the code I have so far:

I have a Joy model that has_many comments.

<% @joys.each do |joy| %>

<ul id="comments-<%= joy.id %>">
  <% joy.comments.where(void:'f').each do |comment| %>
    <li><%= comment.body %></li>
  <% end %>
</ul>

<%= form_with(model: [ joy.user, joy, joy.comments.build ], data:{ "js-comments-#{joy.id}" => true}) do |f| %>
  <%= f.text_area :body, :class=>'form-control', :required=>'true' %>
  <%= f.submit "Post Comment" %>
<% end %>

<script>
  $(document).ready(function() {
    $('[data-js-comments-<%= joy.id %>]').on("ajax:success", function(event, data, status, xhr){
      $('#comments-<%=joy.id%>').append(xhr.responseText);
    });
  });
</script>

<% end %>

In my Comment controller, in my 'create' action, I have:

if @comment.save
  render partial: "comment", locals: {comment: @comment}
end

In my Comment views, I created a partial, called _comment.html.erb:

<li>
    <%= comment.body %>
</li>

So, now when I enter a comment, and click 'Post Comment', it correctly saves my Comment, but it does not ajax load the comment into list. Furthermore, the form does not refresh either. The text remains in the text box. It is not only until after I refresh the page when my comment shows up in the list. Anyone with any thoughts on what I'm missing or doing wrong???

Your help is greatly appreciated in advance.

1 个答案:

答案 0 :(得分:0)

form_with这是一个远程表单,你不需要那个块<script>..</script>。 只需使用create.js.erb,然后使用jquery附加新评论。

如果您想检查邮件是否已成功创建,可以在控制器中添加@status值。

//comments_controller.rb
def create
  ...
  if @comment.save
    @status = "success"
  else
    @status = "failed"
  end
  ...
end

//create.js.erb - for example
 $("#yourCommentList").append('<%= j( render partial: 'comments/comment', locals: @comment ) %>');
 <% if @status == "success" %>
   $("body").append(...your notification...)
    ...
 <% else %>
    ...
 <% end %>