1

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.

1

1 Answer 1

6

The basic idea is that:

  1. You store your latest entry that's been loaded in some way that is accessible to javascript, such as in a data- attribute
  2. You loop ajax calls with a delay
  3. The response of the ajax call will produce changes in your DOM

1

View (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>

2

Javascript:

function poll(){
  latest_id = $('div.image:first').data('id')
  $.getScript('/images?latest_id='+latest_id)
}

$(function(){setInterval(poll, 5000})

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @bdares! Just want to check where I put the javascript in section 2?
Just paste it straight into application.js at the bottom ?
Hey dude, I can't seem to get this going? It's not giving me any errors it's not just updating at all :( is there a good way to tell if it's trying to do anything?
You'll want to look at the server log and browser console for ruby and javascript errors, respectively.
Thanks dude, the concept looks good I'm just having trouble getting it to work :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.