1

I'm using jQUERY+AJAX to refresh a couple of divs every X seconds. I'd like to know what would be the way to load these divs immediately (for the first time) after the page was loaded and then wait (for eg. 30 seconds) for every refresh. I've seen around that you name a function and then call the refresh. The truth is that I can't figure it out how to work it out with my code.

Here are my lines of code:

// <![CDATA[
    $(document).ready(function() {
    $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
    setInterval(function() {

    //DIVs that are being loaded
    $('#item01_tobeloaded').load('items/item01.php');
    $('#item02_tobeloaded').load('items/item02.php');

 }, 30000); // the "30000" here refers to the time to refresh the div. it is in milliseconds.

    });
    // ]]>

Any help will be really appreciated :)

Thanks!

nicozica
  • 423
  • 6
  • 18

1 Answers1

2
<script type="text/javascript">
     $(document).ready(function() {
       $("#refresh").load("refresh.php");
       var refreshId = setInterval(function() {
          $("#refresh").load('refresh.php?' + 1*new Date());
       }, 1000);
    });
</script>

This little script loads and refreshes the div 'refresh' continuously, you can adjust it to your needs by changing 1000 to whatever value you need. 1000 will refresh it every second.

This line

$(document).ready(function() {
$("#refresh").load("refresh.php");

loads yor content on document ready, afterwards you can stick with your code

baao
  • 71,625
  • 17
  • 143
  • 203
  • Thanks brother! In fact, I have more than two divs. Do I have to recall every single div again? Or is there something to help reduce the amount of code? Thanks for your quick reply! – nicozica Nov 01 '14 at 20:16
  • as your page which is refreshed seems to be different for every div (of course) you will need to do this for every div, but you could write a simple function which reduces yor code. Please mark the answer as correct if it has helped you. – baao Nov 01 '14 at 20:24
  • 1
    you might want to look at pjax (https://github.com/defunkt/jquery-pjax) or dotimeout (http://benalman.com/projects/jquery-dotimeout-plugin/) – xeo Nov 01 '14 at 20:45
  • Thanks Mike! I'm trying to figure out out how to enclose the function an then set the timer. I know this is an easy task to do, but it seems I have some syntax mistakes. – nicozica Nov 01 '14 at 21:39
  • Despite it will work, it's not the best approach. Take a look at [this thread](https://stackoverflow.com/questions/48483843/how-to-refresh-a-div-with-a-function-of-print-statements-and-images-in-php-every/48623787#48623787) – moreirapontocom Feb 05 '18 at 13:43