Reputation: 303
I was wondering if anyone could help me with an issue I'm having working out some AJAX in Rails. I'd like to try and do something simple, I just want to constantly check the index view for a new entry with will happen off screen?
Every few seconds it would be really cool for the new entry would just fade in? The new entries are inside a div class called image, and inside that is this:
<%= image_tag image.image_url(:medium).to_s %>
I've tried a few tutorials but some seem out of date of a little off what I'm trying to achieve. I hope someone can help me in the right direction.
Upvotes: 1
Views: 619
Reputation:
The basic idea is that:
data-
attributeView (images/index.html.erb):
<% render @images %>
View (images/_image.html.erb):
<div class="image" data-id="<%=image.id%>">
<%= image_tag image.image_url(:medium).to_s %>
</div>
Javascript:
function poll(){
latest_id = $('div.image:first').data('id')
$.getScript('/images?latest_id='+latest_id)
}
$(function(){setInterval(poll, 5000})
Controller:
@images = Image.order('id desc')
@images = @images.where('id > ?', params[:latest_id]) if params[:latest_id]
View (images/index.js.erb):
$('div.image:first').before('<%=j render @images%>').hide().fadeIn()
Note that I've made some assumptions about your model name and paths. You should modify the paths as needed.
This example is for illustrative purposes and is not suitable for real applications - if the server is overloaded, the javascript will keep hammering it with requests, or if your initial page had no initial entries, the way that new entries are inserted will break.
Upvotes: 6