Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto refresh <div> without reload entire page

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:

  • First Link
  • Second Link

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')
like image 392
dp.carlo Avatar asked Mar 07 '13 14:03

dp.carlo


People also ask

How do I change the content of a page without reloading it?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

How do I automatically refresh part of an HTML page?

Refreshing part of a page periodically You can use the frame “reload” function periodically in frameset page itself. In the above code, “right_frame” reloads every second. setInterval() function is very closely related to setTimeout() – both have similar syntax: setInterval ( expression, interval );


1 Answers

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.

like image 194
Silambarasan R.D Avatar answered Oct 11 '22 02:10

Silambarasan R.D