user2720970
user2720970

Reputation: 294

Live data update with PHP

I have an API which works well, however I would like it to be live (get data periodically from API and show it in my html code).

I just need some hint that from where I most start. Javascript, Ajax?

Any clue would be appreciated.

My PHP / HTML:

<h4>Cpu Load</h4>
<span class="text-muted"><?php 
    echo "" . $first['cpu-load'] . " %" . ""; 
?></span>

Which outputs 2% or whatever. On refresh the page updates the new value.

My PHP API:

<?php
 require('includes/routeros_api.class.php');
  $API = new RouterosAPI();
   $API->debug = false;
    if ($API->connect('MYIP', 'USER', 'PASS')) { 
      $ARRAY = $API->comm("/system/resource/print");
        $first = $ARRAY['0'];
  $API->disconnect();
 }
?>

Upvotes: 0

Views: 10790

Answers (2)

Tim Strawbridge
Tim Strawbridge

Reputation: 655

To keep things simple you could create a function that has your ajax call. You should look up the .ajax jquery usage, but this gives you an idea.

function ajaxQuery(){
    // some stuff inside here to perform call
    $.ajax({
        url: 'your-file.php',
        dataType: 'what ever data type you expect from server...',
        success: function(data) {
            // this is where i would normal have an id setup to update 
            // a specific textbox or form field...
        }

   });


}

You will then have to use the javascript timer function setInterval() somewhere on your page:

setInterval(ajaxQuery(), 2000);

Upvotes: 1

FloatFlower.Huang
FloatFlower.Huang

Reputation: 120

Use setInterval function to query the API every certain time: https://www.w3schools.com/jsref/met_win_setinterval.asp

The convenient way for me is using Vue and Vue-resource via data-binding, after querying API and change data, the page will be re-rendered without refresh the whole page.

Upvotes: 0

Related Questions