Вопрос

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();
    }
?>
Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top