Goose
Goose

Reputation: 4821

PHP echoing setTimeout() to javascript

I have an ajax application using PHP. It loads videos, and ajax needs to load another video after a variable number of seconds it gets from the database. I am trying to echo a setTimeout along with the video, like so, with loadContent being the function that loads videos.

            echo '<iframe id="youtubeFrame" src="//www.youtube.com/embed/
            '.$row['youtube'].'
            ?autoplay=1" frameborder="0" allowfullscreen></iframe>';

            $refreshTimer = $row['end'] - $time;
            $refreshTimer = $refreshTimer * 1000;
            echo $refreshTimer;
            echo '<script>
            setTimeout(loadContent, '.$refreshTimer.');
            </script>';

The video loads, the variable refreshTimer is the right amount of seconds, but it won't run the setTimeout.

How do I get the page to refresh when my database tells it to?

UPDATE: I've been told the variable needs to be turned into an Int, but that can't be the case, because when there is no video, this code runs.

        echo '<h1>Upload content to start the show</h1>';

            echo '<script>
            setTimeout(loadContent, 4000);
            </script>';

This doesn't involve any php variables, it is a direct number, and this doesn't work as well. I'm curious on how to pass data to ajax through the success, but I'm having trouble looking up relevant information online when searching.

Upvotes: 0

Views: 2521

Answers (1)

Sir
Sir

Reputation: 8280

My best guess based on your information provided is the PHP variable will be considered a string and not an integer.

So convert it like this:

echo '<script>
 setTimeout(function(){loadContent();}, parseInt('.$refreshTimer.'));
</script>';

Side note it would be wise to learn how to seperate PHP and JS (server side and client side) using ajax in the future :)

Upvotes: 1

Related Questions