0

I have a .json file with data from Wi-Fi thermometer and I need to upload this data to website using PHP.

Then using JavaScript I need to rewrite the data on the website each few seconds with a new one from the same file.

I have following code:

         <script type="text/javascript">

              function Load()
              {
                <?php
                $json = file_get_contents('data.json');
                $data = json_decode($json, true);
                ?>


                var h = "<?php echo("Humidity: " . $data['humidity'] . "%");?>";
                var t = "<?php echo("Tempature: " . $data['tempature'] . "°C");?>";
                  document.getElementById("hum").innerHTML = h;
                  document.getElementById("temp").innerHTML = t;

              }

              setInterval(Load, 10000);

         </script>

              <div>
                <p id="hum"></p>
                <p id="temp"></p>
              </div>

Although there is setInterval(jsonDataLoad, 10000), it loads the data from the .json file and writes them to the website, but only once when the webpage loads.

So, am I doing something wrong or is the some restriction in PHP or JavaScript, thats causing the code to not work properly?

4
  • 10000 is 10 * 1000 which is 10 seconds, not 1 Commented Oct 28, 2020 at 15:54
  • I don't see any ajax. Your hardcoding all the values in the script (take a look at the generated HTML) and there is no refreshing whatsoever. Commented Oct 28, 2020 at 15:57
  • But where is ajax in your code? Commented Oct 28, 2020 at 16:13
  • 1
    your codes (file_get_contents) will only be rendered once and will stay to be the same regardless of how many times the javascript is repeated thru the setInterval function. Hence you will not be able to load new data --- please consider using ajax to repeatedly call a code on a server (say a php file) which when it is done it will update your DIV contents. Commented Oct 28, 2020 at 16:17

1 Answer 1

0

I think you should write a ajax using jquery to get the JSON content (say function known as getdata());

and then use setInterval to trigger this getdata function in each say 10 seconds

The ajax will then update contents of the DIV.

Please find below a typical jquery AJAX

$.ajax({
  url: "http://test.com/getJSON.php",
  beforeSend: function() {
//    any codes you need
  }
})
  .done(function( data ) {
    if (1==1) {
// the codes to update the DIV
    }
  });
Sign up to request clarification or add additional context in comments.

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.