Search code examples
canvasjs

javascript canvasjs Get data points dynamically from file.txt


Objective:

I want to get data from file.txt thats is saved local in /var/www/html/file.txt and use it for the doughnut chart on my webpage dynamically on a interval of 2 seconds

file.txt only has one entry and looks like:

34

the javascript i have tried:

$.get("file.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({y: parseInt(allLines[i])});
        x += .25;
    }
}
var chart = new CanvasJS.Chart("chartContainer",{
    title :{
        text: "Chart using Text File Data"
    },
    data: [{
        type: "doughnut",
        dataPoints : dataPoints,
    }]
});
chart.render();
});
}

Entire html looks like

<!DOCTYPE html>
<html>
<head>
  <title>Chart using txtfile Data</title>
  <script type="text/javascript" src="http://canvasjs.com/assets/script            /jquery-1.11.1.min.js"></script>
  <script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
 <script type="text/javascript">
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var chart = new CanvasJS.Chart("chartContainer",{
    title :{
        text: "Chart using Text File Data"
    },
    data: [{
        type: "line",
        dataPoints : [function()
        {
        if(allLines.length > 0) {
           for(var i=0; i< allLines.length; i++) {
           xVal +=.25;
           dataPoints.push({x : xVal, y: parseInt(allLines[i])});
    }
}
}]
    }]
});
chart.render();
},'text');
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>

Solution

  • I believe something like this may work for you. You may have to use Firefox as Chrome doesn't like cross origin requests

    First, dataPoints was undefined, I moved the code into a function inside dataPoints. I changed your variable name from x to xVal. Added the 'text' word so the $get knows what format it's reading and also there was an extra bracket it seemed. Give this a try.

        $.get("graph.txt", function(data) {
    var xVal = 0;
    var allLines = data.split('\n');
    var dps = [];
    
    for(var i=0; i< allLines.length; i++) {
       xVal +=.25;
       dps.push({x : xVal, y: Number(allLines[i])});
    }
    
    var chart = new CanvasJS.Chart("chartContainer",{
        title :{
            text: "Chart using Text File Data"
        },
        data: [{
            type: "line",
            dataPoints : dps
        }]
    });
    chart.render();
    },'text');