Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a Rails 3 partial using AJAX (not a form)

I found a number of questions and answers regarding updating a partial using Ajax after submitting a form. But my question is ?simpler?, I just want to reload a partial every few seconds and load in the new data. This really can't be hard at all, and I remember doing something similar in Rails 2.3 but I can't find the answer anywhere.

Basically, I have a show.html.erb rendering a partial like so:

<div id="latest_post">
    <%= render :partial=>'info/latest', :object=>@user, :as=>:user %>
</div>

The partial file located at app/views/info/_latest

<% post = user.posts.last %>
<h1>Last Post</h1>
<p><%= post.content %></p>

I just want the latest_post div to be updated every 30 seconds. Please help!

like image 671
you786 Avatar asked Oct 08 '22 04:10

you786


1 Answers

Well it turns out the answer is a little complicated:

Step 1: Use Javascript's setInterval function along with jQuery's $.get() function to load a page, say /users/1/posts/latest.

setInterval(function(){
  $.get("/users/1/posts/latest.js", function(data){
    $("latest_post").html(data);
  },
  "html")
}, 30000);

Step 2: Create a latest.js.erb and put it in your app/views/posts folder.

Contents of latest.js.erb:

<%= render partial: 'posts/latest', object: @user.posts.last, as: :post %>

Step 3: Create the above partial with whatever you'd like (if you don't need a partial, you can just write the entire contents of the div in the latest.js.erb file.)

Step 4: Add a latest method to your PostsController, that defines @user, etc. for the latest.js.erb to use.

Step 5: Add get '/latest' to your routes.rb

like image 156
you786 Avatar answered Oct 13 '22 10:10

you786