Uchenna
Uchenna

Reputation: 4089

reloading a page after every 10 sec in rails 3.1

i have a rails 3.1rc4 app and i would like to update a div in my index.html.erb file after every 10sec. I dont no if this can be done via jquery? there use to be a update method but i dont no if it is for only prototype. any sample would be great

Upvotes: 0

Views: 2598

Answers (2)

mrk
mrk

Reputation: 5117

Breaking down your question into sub-tasks, here's what you have to deal with:

  1. retrieve (HTTP GET) html
  2. update a div with the retrieved html
  3. Repeat steps 1 and 2 every 10 seconds

For 1, check out jquery's .get

Description: Load data from the server using a HTTP GET request.

For 2, check out jquery's .html

Get the HTML contents ... or set the HTML contents of every matched element.

For 3, check out the setInterval

Summary
Calls a function or executes a code snippet repeatedly, with a fixed time 
delay between each call to that function. Returns an intervalID.

Final solution,

HTML Code:

<div id="divToChange"></div>

Javascript code

  function update()
  { 
     $.get('/', function(data) 
     {
         $('#divToChange').html(data);
     });
  }
$(document).ready(function($){
  window.setInterval('update()', 10*1000);
});

Upvotes: 1

k_b
k_b

Reputation: 2480

I'm assuming you're familiar with javascript and possibly AJAX (if you need it).

This piece of javascript uses the native setInterval function, which calls the updateDiv function every 10 seconds.

var timer = setInterval(updateDiv, 10000);

function updateDiv() {
  // do update
}

Edit: A complete example without jQuery;

<html>
  <head>
    <script type="text/javascript">         
      var index = 1;

      function updateDiv() {
        document.getElementById("updateMe").innerHTML = index++ + " " + new Date();
      }

      var timer = setInterval(updateDiv, 10000);
    </script>
  </head>
  <body>
    <div id="updateMe" />
  </body>
</html>

Upvotes: 1

Related Questions