Get data from url after specific time repeatedly

The purpose of code below is to get data in table from url source.

Short description of actual situation:
On main page i have a button to redirect to *.php page in code snippet bellow.

With name="button1" I am getting  data

and with id="newButtonID" I am  inserting it in  new row in tables.

I have intention to use select element to chose from time options (5min,15min, 60min) and fill new row with new data. (no any code about it for now, but i did add it because i presume that it will need it for timer interval)

My problem:
Before i continue with code-page logics construction I need a solution how to perform refreshing of data after specific time period.

Pleas instruct me how to reach this goal.

Thank you

<?php
if (isset($_POST['button1'])) 
{ 
$url="https://www.....";
$sfgc=file_get_contents($url);
$json=json_decode($sfgc,true);
$last= $json["last"];
//echo $json["last"];
$timestamp= $json["timestamp"];
//echo $json["timestamp"];
$date = new DateTime("@$timestamp");
$date2= $date->format('Y-m-d H:i:s') . "\n";
} 
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BTC</title>

<style type="text/css">
#timeBtcID{ 
    float: left;
    margin: 10px;
    /* background-color: #e6f2ff;
    border-style: solid;
    border-width: 1px;*/
}
#newBtcID{ 
    float: left;
    margin: 10px;
    /* background-color: #e6f2ff;
    border-style: solid;
    border-width: 1px;*/
}

#oldBtcID{ 
     float: left;
    margin: 10px;
    /* background-color: #e6f2ff;
    border-style: solid;
    border-width: 1px;*/
}
</style>

<script>
  var btcData=[];
  var refButton ;
  var tableBtc;
  var myBtc;
  var textBtc
  var r=1;


function btcIDf(){
var lastV=<?php echo json_encode( $last); ?>;
var timestampV=<?php echo json_encode( $date2); ?>;
    /* for(var i =tableBtc.rows.length - 1; i > 0; i--)
{
    tableBtc.deleteRow(i);
}*/
    //for(var i=1, len1 = 10; i < len1;++i){
       var row = timeBtc.insertRow(r);
       var cell1 = row.insertCell(0);
       cell1.innerHTML = timestampV;
       var row = newBtc.insertRow(r);
       var cell1 = row.insertCell(0);
       cell1.innerHTML = lastV;
       var row = oldBtc.insertRow(r);
       var cell1 = row.insertCell(0);
       cell1.innerHTML = lastV;
         ++r;
    //}
}
   window.onload = function(){
            timeBtc=document.getElementById("timeBtcID");
            newBtc=document.getElementById("newBtcID");
             oldBtc=document.getElementById("oldBtcID");
              newButton = document.getElementById("newButtonID");
             newButton.onclick = function() {
                btcIDf();
            }
        };
</script>
</head>
<body>
  <select id="selectTimeID" >
       <option value="5 min">5 min</option>
       <option value="15 min">15 min</option>
       <option value="60 min">60 min</option>
   </select></br></br>
<input type="button" id="newButtonID" value="New"/></br><br>
<form method="POST" action=''>
<input type="submit" name="button1"  value="Refresh">
</form>
<table id="timeBtcID">
    <tr>
         <td ><?php echo $date->format('Y-m-d H:i:s') . "\n"; ?></td>
    </tr>
</table>
<table id="newBtcID">
    <tr>
         <td ><?php echo $last; ?></td>
    </tr>
</table>
<table id="oldBtcID">
 <tr>
         <td><?php echo $last; ?></td>
    </tr>
</table>

</body>
</html>

Open in new window

Ivan GolubarAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
You want to refresh the page after a certain period of time?
You can do this, reload page after 5 min
<script>
document.addEventListener('load', function() {
   setTimeout(function() {
       window.location.reload();
   }, 300 * 1000);
});
</script>

Open in new window


Although I don't think this is the right call. It looks like what you should be doing is using AJAX to call back to the server to update your interface - reloading the page makes it complicated with having the server to re-render the page taking page state into account.
Ivan GolubarAuthor Commented:
Thank you for the answer. And i agree to use ajax.   Next code is tested and it gives me jason back in console.
I will start now  with adding of timer and  acquiring of specific variables from json array. I think i will do it without any problems and close the question with yours answer.


function btcIDf(){
//var lastV=<?php echo json_encode( $last); ?>;
//var timestampV=<?php echo json_encode( $date2); ?>;
    $.ajax({
  method:"POST",
  url: 'https://www..................../',
  data:  {
    },
    datatype: "text",
    success: function(strdate){
   console.log(strdate);
 
     },
     error: function(error, txtStatus) {
      console.log(txtStatus);
      console.log('error');
    }
 });
    
    /* for(var i =tableBtc.rows.length - 1; i > 0; i--)
{
    tableBtc.deleteRow(i);
}*/
    //for(var i=1, len1 = 10; i < len1;++i){
       var row = timeBtc.insertRow(r);
       var cell1 = row.insertCell(0);
       cell1.innerHTML = timestampV;
       var row = newBtc.insertRow(r);
       var cell1 = row.insertCell(0);
       cell1.innerHTML = lastV;
       var row = oldBtc.insertRow(r);
       var cell1 = row.insertCell(0);
       cell1.innerHTML = lastV;
         ++r;
    //}
}

Open in new window

Ivan GolubarAuthor Commented:
I need help with timer settings .  Code below sets timer interval from select options.
I had troubles before with other elements, so i figured out to search fro element after windows loads.
I can find other elements and use them, but with selectTimeID something goes wrong. First line of code gives me error:
Uncaught ReferenceError: selectTime is not defined

I can't understand what is wrong. Pleas help me.

    var intervalTimer=selectTime.value;
     mytimer = setInterval(newIDf, intervalTimer);
      function getTimer(){intervalTimer= selectTime.value;}
      selectTime.onchang=getTimer;


   window.onload = function(){
           selectTime= document.getElementById("selectTimeID");
           timeBtc=document.getElementById("timeBtcID");
            newBtc=document.getElementById("newBtcID");
             oldBtc=document.getElementById("oldBtcID");
              newButton = document.getElementById("newButtonID");
             newButton.onclick = function() {
                newIDf();
            }
        };
</script>
</head>
<body>
<select id="selectTimeID" >
  <option value="0.2">15 sec</option>
  <option value="1">1 min</option>
  <option value="5">5 min</option>
  <option value="15">15 min</option>
  <option value="60">60 min</option>
</select></br></br>
<input type="button" id="newButtonID" value="New"/></br><br>

<table id="timeBtcID">
    <tr>
         <th >Date time</th>
    </tr>
</table>
<table id="newBtcID">
    <tr>
         <th >Actual</th>
    </tr>
</table>
<table id="oldBtcID">
 <tr>

Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Ivan GolubarAuthor Commented:
I forgot to add this line: intervalTimer= intervalTimer*60000;
This is not the solution of the problem but just to not have timer to trigger in milliseconds.
 
 
selectTime= document.getElementById("selectTimeID");
    var intervalTimer=selectTime.value;
    intervalTimer= intervalTimer*60000;
     mytimer = setInterval(newIDf, intervalTimer);
      function getTimer(){intervalTimer= selectTime.value;}
      selectTime.onchang=getTimer;

Open in new window

Julian HansenCommented:
You need to define selectTime in the global scope so that it is visible in the various event handlers

You set it in the onload - but that has its own scope that is not visible in the selectTimeout function - to get around this add
var selectTime

Open in new window

To the top of your JavaScript code.
Ivan GolubarAuthor Commented:
Hi,
thank you.

if you check attached photo you will see variable declaration and also the error.

I can't understand what i am missing.

Uncaught TypeError: Cannot read property 'value' of undefined
123.jpg
Julian HansenCommented:
Ok but you are setting
var intervalTimer=selectTime.value;

Open in new window

Before selectTime has been assigned!

You are assigning in document load but the code above runs immediately - so it is not going to work.

Move the above code into your on load event handler.
This
  var intervalTimer=selectTime.value;
     mytimer = setInterval(newIDf, intervalTimer);
      function getTimer(){intervalTimer= selectTime.value;}
      // SPELLING ERROR onchang => onchange
      selectTime.onchang=getTimer;


   window.onload = function(){
           selectTime= document.getElementById("selectTimeID");
           timeBtc=document.getElementById("timeBtcID");
            newBtc=document.getElementById("newBtcID");
             oldBtc=document.getElementById("oldBtcID");
              newButton = document.getElementById("newButtonID");
             newButton.onclick = function() {
                newIDf();
            }
        };

Open in new window

Becomes this
window.onload = function(){
  var selectTime= document.getElementById("selectTimeID");
  var intervalTimer=selectTime.value;
  mytimer = setInterval(newIDf, intervalTimer);

  function getTimer(){intervalTimer= selectTime.value;}
  selectTime.onchange=getTimer;

  timeBtc=document.getElementById("timeBtcID");
  newBtc=document.getElementById("newBtcID");
  oldBtc=document.getElementById("oldBtcID");
  newButton = document.getElementById("newButtonID");
  newButton.onclick = function() {
    newIDf();
   }
};

Open in new window

Personally I would do it like this
Change select to the following
(i.e. remove 'min' from the option value - just specify value as numeric minutes)
<select id="selectTimeID" >
  <option value="5">5 min</option>
  <option value="15">15 min</option>
  <option value="60">60 min</option>
</select></br></br>

Open in new window

<script>
// ON LOAD
window.addEventListener('load', function() {
  // NO INTERVAL RUNNING YET
  var interval = false;

  // TICK COUNT
  var tick = 1;

  // INITIALISE INTERVAL TO 5 min
  setTimer(5);

  // SETUP onchange EVENT HANDLER. WHEN INVOKED SET TIMER TO NEW VALUE
  // BASED ON SELECTED VALUE IN DROPDOWN
  document.getElementById('selectTimeID').addEventListener('change', function() {
    setTimer(this.value);
  });
  
  // FUNCTION TO SET / RESET INTERVAL
  function setTimer(minutes)
  {
    // IF WE ALREADY HAVE AN INTERVAL RUNNING - CLEAR IT
    if (interval) clearInterval(interval);

    // SET interval TO NEW INTERVAL BASED ON VALUE
    interval = setInterval(intervalFunction, minutes * 60 * 1000);
  }
  
  function intervalFunction()
  {
    // CODE TO HANDLE INTERVAL TIMEOUT
  }
});
</script>

Open in new window


Working sample here

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.