0

I am trying to Plot a live graph using CanvasJS. I have a single JSON file that keeps getting updated by another program. I am trying to read values (Integer) from that file and plot a graph using those values.

I have a code ready but it's not working properly and trying to resolve the issue.

Here is code that directly runs but can't plot the graph.

<!DOCTYPE HTML>
<HTML>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () 
{
    var dataPoints = [];
    var xVal = 0;
    var updateInterval = 1000;
    var dataLength = 40;

    var chart = new CanvasJS.Chart("chartContainer",
    {
        title:{
            text:"Rendering Chart with dataPoints from External JSON"
        },
        data: [{
            type: "line",
            dataPoints : dataPoints,
        }]
    });

    var updateChart = function (count) 
    {
        count = count || 1;

        for (var j = 0; j < count; j++) 
        {
            $.getJSON("gfgdetails.json", function(data) 
            {  
                $.each(data, function(key, value)
                {
                    dataPoints.push({
                    x: xVal, 
                    y: parseInt(value[0])});
                }); 
            });
            xVal++;
        }

        if (dataPoints.length > dataLength) 
        {
            dataPoints.shift();
        }

        chart.render();
    };
    updateChart(dataLength);
    setInterval(function(){updateChart()}, updateInterval);
}
</script>

</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>

Here is the sample JSON file

[
{"NoofProblems":" 20"}
]

Do let me know where I am making a mistake.

Mahadev
  • 856
  • 1
  • 17
  • 44
  • You are not handling the fact that `$.getJSON` is asynchronous correctly. See duplicate for details. – CBroe Sep 20 '22 at 07:30
  • Thank you for the details but I didn't understand what you are saying, – Mahadev Sep 20 '22 at 07:55
  • At the point when `if (dataPoints.length > dataLength)` executes, you have not actually pushed anything to `dataPoints` yet - _because_ $.getJSON is asynchronous. The duplicate contains extended explanations of the problem, and how it can be handled. – CBroe Sep 20 '22 at 07:57

0 Answers0