thenashone
thenashone

Reputation: 249

Refreshing a div with php contents

I am using a webcam to take photos for a learning project I am currently working on and trying to display the images that have just been taken.

When a photo is taken its placed in a folder and wishing to display all the photos taken, inside the <div> I am needing to refresh will be the PHP code to display them.

I have created a simple div with an PHP file named testdata.php which echo's a random number to see if i could get this to work.

I originally pulled the script from a similar question on stackoverflow, but cant get it to work.

<script type="text/javascript">
          $(document).ready(function () {
             $('#mydiv').delay(10000).load('testdata.php');
          });
      </script>


 <div id="mydiv"></div>

The problem is it displays the contents of the file but it doesn't refresh it

here is the code for testdata.php

<?php
echo(rand(10,100));
?>

Upvotes: 1

Views: 60

Answers (3)

dimlucas
dimlucas

Reputation: 5131

You can use JavaScript's setInterval to periodically call a function to load contents from the server.

So if you want to execute the PHP script, say every 5 seconds, then you should use something like this:

$(document).ready(function () {
             setInterval(function(){ $('#mydiv').load('testdata.php') }, 5000);
});

Upvotes: 2

Lucas S.
Lucas S.

Reputation: 2401

Your code is only run once after the page loaded. You will need to execute it periodically:

$(document).ready(function () {
    setInterval(function() {
        $('#mydiv').load('testdata.php');
    }, 10000);
});

This will execute the load-function once every 10000 milliseconds.

Upvotes: 2

Refilon
Refilon

Reputation: 3489

Use this:

setInterval(function(){
     $('#mydiv').load('testdata.php');
}, 3000);

This will execute the function every 3 seconds.

Read more about setInterval here

Upvotes: 3

Related Questions