Warm tip: This article is reproduced from stackoverflow.com, please click
ajax html javascript jquery php

Refresh part of my php page with setInterval()

发布于 2020-03-27 15:41:17

I have a value on my PHP page and I want to refresh it per second with setInterval().

So I actually know how to refresh values with html etc. But now I want to do the same with php values. Here is my code:

<script>
setInterval(function()
    {

<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';

// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);

//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);

//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);

//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);

$formatMachineActive = 'H:i:s'; 

$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);

?>

},1000);

</script>

Ofc this isn't working since JS and php arent really great together. and in my table I just simply have:

<table>
    <tr>
        <td>Activity:</td>
        <td><p id='MachineActivity'></p><?php echo $TimeMachineActive; ?></td>
    </tr>
</table>

So the problem now is, it's only refreshing when I press f5. But now I want the autorefresh. I know setInterval() worked for html. Is it possible to get this done for php code?

Questioner
Bart
Viewed
83
Hammad 2015-03-18 20:58

This should work for you:

JS Code:

<script>
setInterval(function()
{

    $.ajax({

    url: 'value-generation.php',
    type: 'get',
    success: function(response){

    $("#MachineActivity").html(response)
    },

    });

        },1000);

    </script>

value-generation.php code:

<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';

// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);

//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);

//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);

//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);

$formatMachineActive = 'H:i:s'; 

$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);

echo $TimeMachineActive;

?>