-2

Say I have 2 divs, how I can I refresh them both every 5 seconds with 1 ajax request?

<div id='1'></div>

<div id='2'></div>

I can refresh 1 like this:

  interval = setTimeout(refreshpage, 5000);
  function refreshpage() {
     $('#1').load('page.php?&timer='+new Date().getTime()+' #1');
     interval = setTimeout(refreshpage, 5000);
  } 
DobotJr
  • 3,929
  • 9
  • 36
  • 49
  • What do you mean, with 1 ajax request? you can't get 2 pages at the same time. You can create 2 ajax reqeuests that resolve promises, defer them, and call `$.when()` for when they both complete, but other than that, no. – Ohgodwhy Nov 06 '14 at 20:37
  • Don't use `.load()` as that displays the results in the jQuery object you chain it to. Instead use `$.get()` or `$.ajax()`, return json and process the different parts in the ajax success function. – jeroen Nov 06 '14 at 20:37
  • @ohgodwhy the divs are are the same page. – DobotJr Nov 06 '14 at 20:38
  • @jeroen example please? – DobotJr Nov 06 '14 at 20:39
  • You should check the jQuery manual and there are lots of examples here on SO. – jeroen Nov 06 '14 at 20:40
  • 1
    You should never assume that the call is completed at a certain point – Johan Nov 06 '14 at 20:41

2 Answers2

3

So, assuming you want the same ajax call to populate the 2 different div's you would do something like this:

Here's your HTML:

<div id='1'></div>
<div id='2'></div>

So, you can just do the ajax request individually and then load that same request into the 2 divs:

interval = setTimeout(refreshpage, 5000);

function refreshpage() {
    var data = $.get('page.php?&timer='+new Date().getTime()+' #1').done(function (response) {
        ('#1').html(response);
        ('#2').html(response);
    });

    interval = setTimeout(refreshpage, 5000);
} 
Kyle Goode
  • 1,108
  • 11
  • 15
0

What you actually can do is set a timer with setTimeOut function a

 setTimeout(function(){ . . Your ajax Request goes here

 var datos = $.get('page.php?&timer='+new Date().getTime()+'
 #1').done(function (res) {
         $('#1').html(res);
         $('#2').html(res); . . }, 3000);
Kross
  • 97
  • 1
  • 10