June Lewis
June Lewis

Reputation: 355

Jquery Ajax only Works one time

I have a page that is reloading the data in a div, I am using jquery to update the div, but it only fires once.

My page looks like this:

<html><head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
</head><body>
<div id="messages" style="width:100%;font-size:120%;">
  <?php echo $tbl; ?>
</div>
<script type="text/javascript">
$(document).ready (function () {
    var updater = setTimeout (function () {
        $('div#messages').load ('new_hud.php?update=true');
    }, 2000);
});
</script>
</body></html>

I am expecting the script to load the data every 2 seconds. It initialy reloads the data after the first 2 seconds, but then never does again. What am I missing here?

Upvotes: 0

Views: 319

Answers (4)

Defesa Esquerdo
Defesa Esquerdo

Reputation: 320

The setTimeout function by itself won't cycle your script every 2 seconds so what your code is doing is basically waiting 2 after the page is ready to load the data and that's it.

Wrap the setTimeout in a 'for' or 'while' cycle to load the number of times you want.

Hope it's useful :)

Upvotes: 0

j08691
j08691

Reputation: 207861

You're using setTimeout() and want to use setInterval().

var updater = setInterval (function () {

Upvotes: 0

bhspencer
bhspencer

Reputation: 13560

You need to use setInterval rather than setTimeout.

setTimeout will fire once after a specified delay.

setInterval will fire repeatedly with the specified interval.

$(document).ready(function () {
    var updater = setInterval(function () {
        $('div#messages').load('new_hud.php?update=true');
    }, 2000);
});

Upvotes: 1

potatopeelings
potatopeelings

Reputation: 41075

Replace setTimeout with setInterval, like so

var updater = setInterval(function () {
    $('div#messages').load ('new_hud.php?update=true');
}, 2000);

Upvotes: 2

Related Questions