Want to find the answer? Check out this link:
Render a view in rails via AJAX and controller
In my Rails application, I have a Post model that automatically creates and saves new posts while deleting old ones every 10 seconds using an AJAX call set within a setInterval() function in my application.js file:
var post_value = 0;
setInterval(function(){
$.get('https://api.test', function(data){
post_value = data.result.c[0];
});
$.ajax({
type: "POST",
url: "/posts",
data: { parameter: post_value }
});
}, 1000);
The AJAX calls work smoothly saving new posts and deleting old ones. Here is the corresponding controller code:
def index
@posts = Post.all
@bet_last = Bet.last
end
def create
@post = Post.new
@post.value = params["parameter"]
@post.save
Post.first.destroy
@last_post = Post.last
@posts = Post.all
render "index"
end
Below you can see the template HTML view (index.html.erb) for displaying the posts dynamically:
<% @posts.each do |p|%>
<tr>
<th scope="row"><%= p.id%></th>
<td>...</td>
<td><%= p.value%></td>
<td>Active</td>
</tr>
<%end%>
I am facing challenges in updating the page dynamically without refreshing it when new posts are added or deleted. Any suggestions on how to achieve this?
Thank you for your assistance.
EDIT:
Using the following render statement in the controller instead of render "index" seems to solve the issue:
render :js => "window.location = '#{root_path}'"
However, this approach causes the page to reload, which is not the desired outcome.