0

I'm student with no programming experience, but for a project I need to get a txt file into my Javascript chart on the HTML web page. I already tried a lot but I just cant seem it to manage it. The txt file is local and in the same folder as the html. The txt file: [[0,8],[1,10],[2,14],[3,17],[4,13],[5,8],[6,8],[7,13],[8,10],[9,13],[10,14],[11,15],[11,15]]

In this code a chart is made with values of a website, but I need to get its values from a local txt file. I have no clue how to make this work. I hope someone can help to make the code work with local txt file. code

<!DOCTYPE HTML>
<html>

<head>
  <script>
    //chart
    window.onload = function () {

      var dataPoints = [];

      var chart = new CanvasJS.Chart("chartContainer", {
        theme: "light2",
        title: {
          text: "Live Data"
        },
        data: [{
          type: "line",
          dataPoints: dataPoints
        }]
      });
      updateData();

      // Initial Values
      var xValue = 0;
      var yValue = 10;
      var newDataCount = 6;

      function addData(data) {
        if (newDataCount != 1) {
          $.each(data, function (key, value) {
            dataPoints.push({
              x: value[0],
              y: parseInt(value[1])
            });
            xValue++;
            yValue = parseInt(value[1]);
          });
        } else {
          //dataPoints.shift();
          dataPoints.push({
            x: data[0][0],
            y: parseInt(data[0][1])
          });
          xValue++;
          yValue = parseInt(data[0][1]);
        }

        newDataCount = 1;
        chart.render();
        setTimeout(updateData, 1500);
      }
      function updateData() {
        $.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=" + xValue + "&ystart=" + yValue + "&length=" + newDataCount + "type=json", addData);
      }

    }


  </script>
</head>

<body>

  <div id="chartContainer" style="height: 370px; width: 100%;"></div>
  <script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
  <script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
</body>

</html>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Does this answer your question? [How to read an external local JSON file in JavaScript?](https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript) – derpirscher Jan 24 '21 at 10:16
  • Does this answer your question? [Loading local JSON file](https://stackoverflow.com/questions/7346563/loading-local-json-file) – pilchard Jan 24 '21 at 10:22
  • @derpirscher HI I have some difficulties to understand what they are doing. I also tried some code of there but it doesnt work for me? Can u perhaps show me some example code for it? – OS_Research Jan 24 '21 at 10:29
  • @pilchard Hi, as far I saw that question only shows where u can open browser and then select a file, but I want that it automatically opens the same file everytime – OS_Research Jan 24 '21 at 10:32
  • You don't need to open the file more than once, simply load it, store the data in a variable, and then access that data sequentially as needed to update the chart. – pilchard Jan 24 '21 at 10:35
  • @pilchard Sorry for asking this but can u show me how this need to be coded....? – OS_Research Jan 24 '21 at 10:37

3 Answers3

0

There are two approaches that I can think of:

Host a webserver

You can host a webserver that will expose an API that your HTML will be able to call via AJAX in order to obtain the content of your txt as a JSON. Anatomy:

  • webserver
    • is able to load your txt
    • exposes an API that can be reached via an HTTP request
    • that API will load your txt and send its content as a response
  • HTML
    • requests the webserver in order to obtain your JSON
    • uses the response as your input for the chart

Run browser from command-line

You can also create an HTML file where you will know where you need to put your JSON (a JS initialization, perhaps) and you could write a CLI application that loads your JSON from the txt, modifies your HTML file so that the JSON will be written into it and then run your browser via cli, see this example: https://www.howtogeek.com/663927/how-to-open-google-chrome-using-command-prompt-on-windows-10/

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

I tidied up your script a little bit. There were a few points amiss:

  • you rendered your chart outside the callback function of the $.getJSON() call. This means that you were renderering before you actually received any data.
  • there was a typo in your url: an ampersand & was missing before the type part.

Apart from that I shortened you data import part in the updateData() function.

var dataPoints=[], chart = new CanvasJS.Chart("chartContainer",
 {theme: "light2",title: {text: "Live Data"},
  data: [{ type: "line", dataPoints: dataPoints}] });

updateData(1,1,10);                        // first time round 
setTimeout("updateData(11,1,10)", 1500);   // second time after 1.5 seconds
setTimeout(()=>updateData(21,1,10), 3000); // third time after another 1.5 seconds

function addData(data) {
  data.forEach(([x,y])=>dataPoints.push({x,y}));
  chart.render();
}
function updateData(xValue,yValue,newDataCount) {
  $.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=" 
             +xValue+"&ystart="+yValue+"&length="+newDataCount+"&type=json", addData);
}
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
  
<div id="chartContainer" style="height: 370px; width: 100%;"></div>

I put the delayed function call "updateData(11,1,10)" in quotation marks into the setTimeout() call. Had I put it in there without them then the function would have been executed directly and its (undefined) return value would have been "executed" after the 1500 milliseconds.

Edit: I edited my code further, putting the chart.render() call into the addData() unction. This way I can make sure that the chart is always freshly rendered after data has been added into it.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • Hi, when I look at the code I see it is getting still its values from a website right? – OS_Research Jan 24 '21 at 10:50
  • I edited it a bit, but - yes - the values are from the external website. – Carsten Massmann Jan 24 '21 at 11:04
  • Hi thanks for the edit, but I would like that the values are from a local file, can u help me with that – OS_Research Jan 24 '21 at 18:25
  • Hi thanks for the edit, but I would like that the values are from a local file, can u help me with that – OS_Research Jan 24 '21 at 18:26
  • If you mean "local" in the sense of a user's device (pc, tablet or smartphone) then you will need to provide some kind of upload dialogue, so the user can send the data to your webserver from where the rest can be handled. If - on the other hand - this file resides on your own "local" webserver then it is merely a question of using a relative URL in the `$.getJSON()` call. – Carsten Massmann Jan 24 '21 at 18:33
0

You are looking for D3.js library which can create bar char, line chart, donut chart, pie chart etc.

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered_comma.csv",

  // When reading the csv, I must format variables:
  function(d){
    return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.value }
  },

  // Now I can use this dataset:
  function(data) {

    // Add X axis --> it is a date format
    var x = d3.scaleTime()
      .domain(d3.extent(data, function(d) { return d.date; }))
      .range([ 0, width ]);
    svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

    // Add Y axis
    var y = d3.scaleLinear()
      .domain([0, d3.max(data, function(d) { return +d.value; })])
      .range([ height, 0 ]);
    svg.append("g")
      .call(d3.axisLeft(y));

    // Add the line
    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "steelblue")
      .attr("stroke-width", 1.5)
      .attr("d", d3.line()
        .x(function(d) { return x(d.date) })
        .y(function(d) { return y(d.value) })
        )

})
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<meta charset="utf-8">

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>
  • I tried using d3 before, but d3.csv is the function. But I tried to make it for a txt file, so I dont really how to change it for a txt file – OS_Research Jan 24 '21 at 10:57