13

I'm trying to update the content of "mydiv" without refreshing the entire index page. @mydata is given by mycontroller. I need to recalculate it every n seconds and pass it to "mydiv"

With "link_to" it works!

index.html.erb

<%=
    link_to('refresh', '/mycontroller/index', :remote => true)
%>

<div id="mydiv">
    <%=
        @mydata
    %>
</div>

index.js.erb

$('#mydiv').html('<%= escape_javascript(@mydata) %>')

Now I need to refresh the content of "mydiv" automatically every n seconds (so without click on the link). I have tried solutions from:

but no luck.

In my application.js I have writed this:

function executeQuery() {
  $.ajax({
    //url: '/index',
    success: function(data) {
      $('#mydiv').html(data)
    }
  });
  setTimeout(executeQuery, 500);
}

$(document).ready(function() {
  setTimeout(executeQuery, 500);
});

For who is facing my same problem, I solved it by replacing

$('#mydiv').html(data)

with

$('#mydiv').load('/mycontroller/index #mydiv')
Community
  • 1
  • 1
dp.carlo
  • 597
  • 2
  • 11
  • 28
  • shouldn't it be `window.setTimeout(executeQuery, 500)`? – sjain Mar 07 '13 at 14:23
  • @SaurabhJain I think It's the same. It refresh but It returns all the page into "mydiv". I need to refresh only "mydata" – dp.carlo Mar 07 '13 at 14:28
  • You need to create a page that has only the contents you want instead of loading the complete page. – JJJ Mar 07 '13 at 14:39
  • @Juhana instead of using $('#mydiv').html(data), I have replaced it with $('#mydiv').load('/mycontroller/index #mydiv') and now it works! – dp.carlo Mar 07 '13 at 16:21

2 Answers2

1

Use setInterval() instead of using setTimeout().

Ref: https://www.w3schools.com/jsref/met_win_setinterval.asp

function executeQuery() {
  $.ajax({
    type: 'GET',
    url: 'example.com/url/', // Provide your response URL here.
    success: function(data) {
      $('#mydiv').html(data);
    }
  });
}

setInterval(executeQuery(), (n * 1000)); // Replace 'n' with how many seconds you want.

This code will run the executeQuery() method in every 'n' seconds interval. So that your requirement is accomplished.

Silambarasan R
  • 1,346
  • 15
  • 22
0

Set layout to false in the action and just pass on the relevent content, not the entire page

def action1
   <your code here>
end
def action2
   <your code here>
   render :layout => false
end

Your view for action2 should have content pertaining only to #mydiv.

A better solution would be to use a single action and change render options based on type of request. (Ajax or non ajax)

Sushruth Siv
  • 45
  • 1
  • 8