How to load data from .txt into javascript

Please help me. There is a javascript code, where I make a canvas graph. The data for the graph is there static, but I want to load these datas from a .txt file. Do you know how? Thank you!

<script type="text/javascript">

var canvas ;
var context ;
var Val_max;
var Val_min;
var sections;
var xScale;
var yScale;



        // Values for the Data Plot, they can also be obtained from a external file
var data =[0,10,20,40,50,100,120,130,0];



function init() {
        // set these values for your data 
    sections = 12;
    Val_max = 130;
    Val_min = -40;
    var stepSize = 10;
    var columnSize = 50;
    var rowSize = 50;
    var margin = 10;
    var xAxis = [" ", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 
        //

    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    context.fillStyle = "#0099ff"
    context.font = "20 pt Verdana"

    yScale = (canvas.height - columnSize - margin) / (Val_max - Val_min);
    xScale = (canvas.width - rowSize) / sections;

    context.strokeStyle="#009933"; // color of grid lines
    context.beginPath();
        // print Parameters on X axis, and grid lines on the graph
    for (i=1;i<=sections;i++) {
        var x = i * xScale;
        context.fillText(xAxis[i], x,columnSize - margin);
        context.moveTo(x, columnSize);
        context.lineTo(x, canvas.height - margin);
    }

Upvotes: 1

Views: 52

Answers (1)

James
James

Reputation: 1177

For load file, try this:

function request (path, onload) {
    var req = new XMLHttpRequest();
    req.onload = function () {
        return onload(this.responseText);
    };
    req.open("GET", path, true);
    req.send();
}

and use:

request('http://yousite.com/text.txt',function(response){
    //code here
});

Upvotes: 1

Related Questions