0

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?

domnakus
  • 1
  • 1
  • 2
    Set an interval in your JS and get the data from PHP using Ajax. – Reza Saadati Apr 21 '18 at 10:37
  • Your update suggests a misunderstanding of how AJAX works. In the browser, both the request and the response are handled by Javascript. You can't use PHP for handling the response, since the request is being sent repeatedly long after the page has loaded and PHP is no longer involved. – Boaz Apr 21 '18 at 17:33
  • In PHP, you're probably looking to send a JSON response and in JS to handle a JSON response. Read about those in the many other questions on this topic. – Boaz Apr 21 '18 at 17:35

0 Answers0