0

I am trying to implement jquery replacement for the old periodically_call_remote. I got the following code from another stackoverflow thread here:

$(document).ready(
  function(){
    setInterval(function(){
      $('#mydiv').load('/controller/action');
    }, 3000);
  });

But I am struggling to make it work. If I understand UJS correctly, if I do the following things:

  • Place the script in application.js
  • include application.js in my layout (which javascript_include_tag :defaults does)
  • have a DOM element in my view template with id='mydiv'

Then the function should automatically bind to 'mydiv' and execute after the page is loaded, right? Is there a step I am missing? I should not have to name the function or call it directly in the view, correct?

Second, how can I dynamically update the load URL. For instance, I have a nested resource with the path '/controller/:id/action' ... how do I dynamically insert the :id value into the load path at render time?

Community
  • 1
  • 1
Ed Haywood
  • 335
  • 2
  • 9

2 Answers2

1

Add the following inside you functions.

$('#mydiv').css("background", "red");

Did the color of the div change? If it did, debug your server side code.

If you know how to open a JavaScript console in your browser, open it and see if there are any errors.

Emil
  • 8,449
  • 3
  • 27
  • 44
1

The way to do this unobtrusively is to set an attribute in the div tag that you want to load and then grab it from within the application.js file.

some.html

<div data-delay-load="<%= url_for() %>"></div>

application.js

$(function() {

    $('div[data-delay-load]').each( function() {
        var url = $(this).attr('data-delay-load'),
            $element = $(this);

        var _func = function() {
           $element.load(url);
        }

        setTimeout(_func, 3000);
    });
});

What is nice is that you can have a delay load on any page or multiple elements on the same page just by including the data-delay-load attribute.

natedavisolds
  • 4,305
  • 1
  • 20
  • 25
  • Thanks. After I posted, I realized I didn't need the :id, so I changed my routes declaration so the action was on the collection rather than a member. That allows me to use a simple string for my load url, eg .load('action/controller'). However, for some reason the resulting http request appends the string to the full current url rather than the base url, eg GET base/controller/action/controller/action. Any idea why? – Ed Haywood Jun 22 '11 at 18:55
  • disregard my question, was a simple syntax error, needed slash in front of the path, eg .load('/controller/action') – Ed Haywood Jun 22 '11 at 19:25