Home > Blockchain >  Loading every second new json file in html without reloading the whole page
Loading every second new json file in html without reloading the whole page

Time:04-05

I am pretty new in this stuff and tbh I have no idea of javascript, so sorry for the maybe stupid question. I created two python-scripts. The first one is a flask API. Here I generated a root in '/'. When the request method is 'put', it is taking the data from my python simulation script, which is creating some random data, and storing it locally as a JSON file on the computer. The 'get' method is loading and returning this JSON file. My problem now is, that I like to create something like a dashboard, I like to display on the one hand the data in real-time and on the other hand I like to plot this data. For displaying the data I created a javascript, which is requesting the JSON file and displaying it as values. But somehow, every time I'm overwriting the JSON-file the whole page is reloading and my live plot is not working because of this. How can I suppress this and refresh just the values instead of the whole page?

javascript for loading the values from the request

async function getISS() {
  const response = await fetch("http://127.0.0.1:5000");
  const data = response.json();
  const { Flow, Pressure, Solubility, Temperature, Timestamp, Valve } = data;
  document.getElementById("sol").textContent = Solubility;
}
getISS();

python script for creating the simple API:

import json
from flask import Flask, request
from flask_cors import CORS
import os

app = Flask(__name__)
CORS(app)

@app.route('/', methods=['GET', 'PUT'])
def create_record():
    if request.method == 'PUT':
        record = json.loads(request.data)
        with open('data.json', 'w', encoding='utf-8') as f:
            json.dump(record, f, ensure_ascii=False, indent=4)
        return 'Done'
    elif request.method == 'GET':
        if 'data.json' in os.listdir():
            with open('data.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
            return data
        else:
            return '<body>Data is not available!</body>'

app.run('127.0.0.1', port=5000, debug=False)

I would like to display the values in specific divs without reloading the page, every time a new JSON file is available.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Testbench</title>
    <link rel="stylesheet" href="style.css" />
    <link rel="icon" type="image/png" href="/images/Logo.png" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Smooch Sans&display=swap"
      rel="stylesheet"
    />
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
  </head>

  <body>
    <img  src="images/Logo.png" alt="Logo" />
    <h1 >Testbench</h1>
    <section >
      <div >
        <p >Sensors</p>
        <div >
          <p >Temperature in °C</p>
          <div  id="temperature"></div>
        </div>
        <div >
          <p >Pressure in bar</p>
          <div  id="pressure"></div>
        </div>
        <div >
          <p >Solubility</p>
          <div  id="solubility">
            <p>
              <span id="sol"></span>
            </p>
          </div>
        </div>
      </div>
      <div >
        <p >Test</p>
        <select name="test" id="choosetest">
          <option value="testscene">Choose Test</option>
          <option value="testscene">Cyclus</option>
          <option value="testscene">Some Other Stuff</option>
          <option value="testscene">Again Some Other Stuff</option>
        </select>
      </div>
      <div  id="graph"></div>
    </section>
    <section ></section>
    <script>
      const api_url = "http://127.0.0.1:5000";
      async function getISS() {
        const response = await fetch(api_url);
        const data = await response.json();
        const { Flow, Pressure, Solubility, Temperature, Timestamp, Valve } =
          data;
        document.getElementById("sol").textContent  = Solubility;
      }
      getISS();
      function rand() {
        return Math.random();
      }

      var time = new Date();

      var data = [
        {
          x: [time],
          y: [rand()],
          mode: "lines",
          line: { color: "#80CAF6" },
        },
      ];

      Plotly.plot("graph", data);

      var cnt = 0;

      var interval = setInterval(function () {
        var time = new Date();

        var update = {
          x: [[time]],
          y: [[rand()]],
        };

        var olderTime = time.setMinutes(time.getMinutes() - 1);
        var futureTime = time.setMinutes(time.getMinutes()   1);

        var minuteView = {
          xaxis: {
            type: "date",
            range: [olderTime, futureTime],
          },
        };

        Plotly.relayout("graph", minuteView);
        Plotly.extendTraces("graph", update, [0]);

        if (cnt === 100) clearInterval(interval);
      }, 100);
    </script>
  </body>
</html>

CodePudding user response:

The simpliest way to get this working is to change

document.getElementById("sol").textContent = Solubility;

to this, which will take the textcontent and add on the next bit of data. This is appending the data each time to that element rather than overwriting it each time.

document.getElementById("sol").textContent  = Solubility;

CodePudding user response:

I found my solution. My problem was that I had the JSON file in the same directory as my HTML. Somehow this led to the problem that the script was refreshing all the time. I moved my python scripts to another location and now it's working. Thank you anyway for your help guys. :)

  • Related