Home » Php » php – Making a dynamic graph on a HTML webpage that pulls data from a txt file

php – Making a dynamic graph on a HTML webpage that pulls data from a txt file

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am building a webpage that I want to have a dynamic chart shown to the user. Similar to https://canvasjs.com/html5-javascript-dynamic-chart/ . The webpage needs to pull the data from a txt file, and then update the graph as time goes. The txt file is eventually going to be having data written to it, and I want to be able to plot the data from the txt file to the webpage as it comes in. I have looked around, and https://canvasjs.com/forums/topic/how-can-i-plot-values-from-txt-file/ describes the issue I am facing.
The txt file has values of (to keep it simple):
1
2
3
4
5
6
7
8
9

The code I am trying to run is below, but whenever I open the HTML inside a browser, the screen is blank.

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="jquery-2.1.1.js"></script>
<script type="text/javascript">
window.onload = function () {
var dataPoints = [];

//Replace text file's path according to your requirement.
$.get("testgraph.txt", function(data) {
    var x = 0;
    var allLines = data.split('\n');
    if(allLines.length > 0) {
        for(var i=0; i< allLines.length; i++) {
            dataPoints.push({x: x , y: parseInt(allLines[i])});
            x += .25;
        }
    }
    var chart = new CanvasJS.Chart("chartContainer",{
        title :{
            text: "Chart using Text File Data"
        },
        data: [{
            type: "line",
            dataPoints : dataPoints,
        }]
    });
    chart.render();
});
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>

I’m very confused as to why when I open the browser the screen is blank. The text file is called testgraph.txt and is saved on my desktop (I use Windows 10). And the html file is called test.html and is also saved on my desktop. Any ideas would be very helpful, as I am lost at this point. The end goal is to have numerical numbers coming into the text file, read by the webpage, and then update the graph dynamically.

Thanks,
Tyler

How to&Answers: