Home > Software engineering >  How i can pass real data from my javascript function-script to javascript chart js
How i can pass real data from my javascript function-script to javascript chart js

Time:08-01

this is the chart i want to insert my live int data (counter) from python flask server to the chart i want it to be a live upload chart the data are live but i cant insert the to the chart it disappears

   

<canvas id="myChart" width="400" height="400"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>
 

live data go to test class as a count number 1,2 ,3 ,4 but i cant import that result to chartjs so i wanted to ask how can i take the sensor reading information and create a live chart

<!DOCTYPE html>
<html lang="en">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

<head>
    <meta charset="utf-8">
    <title>Flask App</title>
</head>

<body>


  <div id='test'></div>

<script>
  document.addEventListener("DOMContentLoaded", function(event) {

    const getSensorReading = function() {
      fetch(`http://${location.host}/update`)  // send request to route /update
        .then((resp) => resp.json())
        .then(function(response) {
          document.getElementById('test').innerHTML =response.data.toFixed(1);
      });
    }

    getSensorReading();

    setInterval(getSensorReading, 1000); 
   //request for update every 1 second
  });


  </script>
</body>

</html>

CodePudding user response:

The steps for building this would be along these lines:

  1. Plot your first data point with chartjs. Add this point, do not care (too much about the live data). You can find an example on how to build a simple linechart here: https://www.chartjs.org/samples/2.6.0/charts/line/basic.html. Look into the html, there is a script tag before the closing body tag, that builds the chart.

  2. Keep a reference to the chart. In the example they do that by assigning to the window object. So assigning like this: window.myLineChat = new Chart(container, config). In a browser, the window is the global namespace, so it is not super clean doing so (but probably the least troublesome in the beginning).

  3. Because you have a reference to the chart, you can now update it. If the reference is in the global namespace (your window) you can access it right away, without passing any data - as long as you have already defined the chart. So each time you get new data, you just pass it to your chart. See: https://www.chartjs.org/docs/latest/developers/updates.html

If you use window.myLineChart, the function will change:

function addData(label, data) {
    window.myLineChart.data.labels.push(label);
    window.myLineChart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}
  • Related