0

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.

i.e. 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();
?>
4
  • 6
    Learn the page life cycle of PHP. Commented Apr 17, 2013 at 1:44
  • 1
    You can't do it this way; separate the process and use AJAX to invoke it from the client side. Commented Apr 17, 2013 at 1:49
  • 1
    Here's an hint PHP runs on server side and JavaScript on client side Commented Apr 17, 2013 at 1:49
  • I will try to do this: 1- Put all php code inside new file. 2- Use Ajax POST inside your setInterval function, pass data to php file and recover the info u want to publish Commented Apr 17, 2013 at 1:50

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Yaakov. That explains it much better than my professor. This didn't even come up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.