1

I am trying to post an updating ping on my website, without having it reloading all the time, yet when i try it posts the initial ping, but it doesnt update after the time interval i've set

index.php :

<script>

    setInterval(document.write('<?php echo json_encode(getPingout());?>'),100);
</script>

functions.php :

    <?php    
    function getPingout() {
            // some function that finds the ping of the server
        return $server->getPing();
    }
?>
2
  • 1
    Learn about the page life cycle. Commented Apr 29, 2014 at 16:41
  • To the mods who picked the right answer: w3schools.com? Seriously, there is no better explanation to this guy on stack overflow than a reference to the voldemort of webdevelopment? Commented Apr 29, 2014 at 18:31

2 Answers 2

0

You can't just have php run multiple times after a page has loaded. That PHP is executed one time when the page loads.

To do what you are attempting to do you should use some javascript and an ajax call.

$(function(){
   function pingServer(){
     $.post('/ping.php',function(data){
       console.log('server is ok');
     });
   }

   setInterval( pingServer, 4000 );
});

Also you may not need to ping the server every that often (every 100). Otherwise you may have issues.

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

1 Comment

I found out this was the easiest way for me
0

That is not how javascript & PHP work together.

In order to refresh data without a page reload, you must request the data asynchronously. Search for AJAX or XHR, I really recommend that you look into something like jQuery though, as you will save alot of time writing code and debugging, compared to if you were to write the javascript by yourself.

If you were to do this in jQuery:

//this means run when page is ready
$(function(){
  setInterval(function(){
      //Send POST request to ping.php
      $.post('ping.php',{},function(){
        //Append the result to the body in a new div
        $('body').append($('<div>'+data+'</div>'));
      });
  },100);
});

and your ping.php should simply return the ping and nothing else.

And don't let the dollarsigns confuse you, in PHP its a prefix for variables, but in the javascript/jquery context it simply is a variable, containing the jquery object that you call functions from.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.