How do I execute a PHP function every two seconds inside JavaScript?

2.2k Views Asked by At

I have this PHP function called GetTotalItemsPercentage() which gets the amount of entries in my MySQL database and returns a percent based on the maximum amount of entries that are allowed (returns 50, 40, 39 etc.). However, I want this to update a div's height depending on this percentage. I currently have this code, however after the first update, it doesn't update again.

    <script type="text/javascript">
        setInterval(function() {
            $("#filled-jackpot-display").animate({height:'<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>%'});
        }, 2000);
    </script>

So how would I go about getting it to update every two seconds and constantly change the size of the div? I'm guessing I will have to run a loop in the PHP code and then use echo inside the PHP file to run JavaScript rather than the other way.

2

There are 2 best solutions below

0
On BEST ANSWER

PHP executes on server, javaScript on the client, you have to make a new php file with

<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>

in it, let's call it 'getTotalIP.php' then you call it with ajax.

<script type="text/javascript">
    setInterval($.ajax('getTotalIP'), 2000); //Short answer with jQuery
</script>

If your script is intended to print something then you need more code to parse the answer. A good way to do it is printing the php result in json and parse it with javaScript.

Here you have more cross-browswer ajax information: https://www.w3schools.com/php/php_ajax_php.asp

0
On

You cannot execute PHP on the client side. The way to do this would be to call the php code with ajax() and then animate in the success handler

myscipt.php

<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>

myscript.js

setInterval( function() { 
    $.ajax({url: 'myscript.php', success: function(data){
       $("#filled-jackpot-display").animate({height: data});
}, 2000);

Note, since ajax is asynchronous, it may not smoothly animate in 2 second intervals. If you only need the height once, then load it on ready and proceed to animate in 2 second intervals