Search code examples
jqueryruby-on-rails-3ujs

Rails 3 - Periodic Refresh of DIV


I am trying to refresh the contents of a div using AJAX/Unobtrusive JavaScript/JQuery.

This is easy to do if I make a "refresh" link and give it a data-remote attribute.

However, I would like to refresh every 2 seconds using the setInterval function rather than using a link.

This code should demonstrate what I'm trying to do. It does not work when put in application.js because the ERB is not evaluated, but hopefully it will explain my goal.

  setInterval(function(){
    $("#scuttlebutt").html("<%= escape_javascript(render 'scuttlebutt') %>");
  },2000);

What would be a proper way to do this in Rails 3??

(I am working with Rails 3.2.5)


Solution

  • I ended up putting code in application.js that would:

    • Check if the div exists
    • Make a timer using setInterval
    • Request a js script from Rails at the current URL which would lead to the evaluating of a js.erb view file. When this file was run it would update my div.

    Behold...

    assets/javascripts/application.js

    $(function() {
    
      if ($('#scuttlebutt').length) {
        setInterval(function(){
          $.getScript(window.location.pathname, function(data, textStatus, jqxhr) {
            console.log('Load was performed.');
          });
        },2000);
      }
    
    });
    

    views/tickets/show.js.erb

    $("#scuttlebutt").html(" <%= escape_javascript(render 'scuttlebutt') %>" );