Reputation: 1384
I'm trying to append div into my HTML using AJAX, system was developed in rails. This is the content of js.erb file:
$('.posts').append("<%= j render 'post', posts: @post %>")
I really know that this file is being called by my code because if I change these line to alert.('Hello')
the alert is shown on my web browser.
The problem is that the div is not being added.
Here is the code of my _post.html.erb
<%= div_for @posts do %>
<p><b>Posted <%= time_ago_in_words(post.created_at) %> ago </b></p>
<p><%= post.message %></p>
<% end %>
No errors is shown on terminal or in browser inspector.
[Edit 1] I saw now in chrome editor, server is posting one ajax to client side. The content is:
$('.posts').append("")
Seems like render is not rendering, what is wrong with my code?
[Edit2]
The controller code is below. The method that is calling the ajax is the create. I don't know if this make easier to see, but all this project is on github too:
https://github.com/ricardovsilva/twitter-rubyOnRails/
class PostsController < ApplicationController
def index
@posts = Post.order('created_at desc')
#respond_to :html
end
def create
@post = Post.create(:message => params[:message])
respond_to do |format|
if @post.save
format.html { redirect_to posts_path }
format.js
else
flash[:notice] = "Message failed to save."
format.html { redirect_to posts_path }
end
end
end
end
The HTML's are:
index.html.erb
<%= render partial: "message_form" %>
<div id="posts">
<%= render partial: @posts %>
</div>
_message_form.html.erb
<%= form_tag("/posts", remote: true) do %>
<%= label_tag(:message, "What are you doing?")%><br>
<%= text_field_tag(:message, nil, size: "44x6") %><br>
<%= submit_tag("Update") %><br>
<% end %>
_post.html.erb (this is the one that I'm trying to render and send to client side)
<%= div_for @posts do %>
<p><b>Posted <%= time_ago_in_words(post.created_at) %> ago </b></p>
<p><%= post.message %></p>
<% end %>
layouts/application.html.erb (here is where I'm trying to add the rendered div by ajax)
<!DOCTYPE html>
<html>
<head>
<title>Twitter</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div id="content">
<%= yield %>
</div>
</body>
</html>
Upvotes: 2
Views: 2106
Reputation: 321
$('#posts').append("<%= j render 'post', post: @post %>")
is solution for your problem. Also _post.html.erb must be:
<%= div_for post do %>
<p><b>Posted <%= time_ago_in_words(post.created_at) %> ago </b></p>
<p><%= post.message %></p>
<% end %>
Upvotes: 1
Reputation: 9961
In your case you should render post
template to string using render_to_string method.
Upvotes: 0