I'm programming a slideshow with php and js. Currently i'm reading the images via scandir() at the beginning of my php document and parsing the array to my javascript.
<?php
$dir = 'images';
$data = scandir($dir, 1);
$dirdata = array_slice($data, 0, count($data)-2);
?>
<script>
var data = <?php echo json_encode($dirdata, JSON_HEX_TAG); ?>;
set_data(data);
</script>
set_data() is a function in my javascript to update the array displayed in the slideshow.
Now I want to run this code every 5 seconds to update my array of images, so that new images added to the directory are added to the slideshow. My Problem is that I don't know how to execute both parts of the code within a intervall. I could use a timeout to time the javascript part or the php event queue to loop that part.
Is there a way i could do both in a clever way? Or is there even a easier approach to my problem?
EDIT: I never used AJAX before so now i looked it up and tried it. Now i have a script:
<script>
function update_data() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = <?php echo json_encode(xmlhttp.responseText, JSON_HEX_TAG); ?>;
set_data(data);
}
};
xmlhttp.open("GET", "update_dir.php", true);
xmlhttp.send();
}
var d_timer = setInterval("update_data()",5000);
</script>
The update_dir.php contains:
<?php
$dir = 'images';
$data = scandir($dir, 1);
$dirdata = array_slice($data, 0, count($data)-2);
echo $dirdata;
?>
It still does not work. One the one side there I refer to the js variable in the inner php-environment. Obviously this will not work. But what is a way to get it working?