简体   繁体   中英

PHP code only runs once inside javascript setInterval

I'm just learning PHP and Javascript in a JC class. I have the following for a school project. The following setInterval() runs every 3 seconds, however the embedded PHP code only runs the first time.

ie newVal gets updated the first time but doesn't change it's value on the following iterations. The script never telnets back into the server to find if the value changed.

 setInterval(function () {
    var newVal, mem;

    <?php $telnet = new PHPTelnet();?>;
    <?php $result = $telnet->Connect('ip_address','username','password');?>;
    <?php   $telnet->DoCommand('show process memory summary"', $result);?>;
    <?php $result = preg_replace('/[\r\n ]+/',' ', trim($result)); ?>;

    newVal = "<?php echo substr($result,61,7) ?>"; 
    newVal = newVal / 10000;

    mem.update(newVal);
  }, 3000);

Thanks to some of the answers/comments below, this is what I did to make it work:

Javascript

     setInterval(function () {
        $.get("memAccess.php", function(return_value) {
                mem.update(parseFloat(return_value));
        });
    }, 3000);

Separate PHP file

<?php
    $telnet = new PHPTelnet();
    $result = $telnet->Connect('ip_address','username','password');

    $telnet->DoCommand('show process memory summary', $result);
    $result = preg_replace('/[\r\n ]+/',' ', trim($result));
    $result = substr($result,61,7);

    echo $result; 
    $telnet->Disconnect();
    exit();
?>

Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)

So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.

more on Ajax: Ajax Basics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM