I'm working on a small web app. I should be able to upload a .csv file and it gets parsed into an array.
However, the javascript only works when I am using the developer tools (in firefox or chrome) and have a breakpoint in the code. The breakpoint can be on any line of code and it reads and parses the file fine but it won't work properly without it. Without the breakpoint the javascript runs to completion but my 'parsed' variable is still empty. With a breakpoint and then stepping through the code my test data is parsed into an array as expected.
I'm using d3 to parse the data as I am going to use it for some graphs later on.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>IMLE</title>
<script src="https://d3js.org/d3.v5.js"></script>
<script data-require="jquery@2.1.3" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="site.css">
<script src="site.js"></script>
</head>
<body>
<div id="page">
Import your data...
<div id="import">
From:
<div id="importbtns">
<form enctype="multipart/form-data" method="POST">
<input name="file" type="file" id="fileval"/>
<input type="submit" value="Upload" id="Upload" onclick="myFunction()"/>
</form>
</div>
Supported types are: .csv
</div>
</div>
</body>
</html>
Javascript:
function myFunction() {
var item = document.getElementById("fileval");
var file = item.files[0];
var parsed = {};
var reader = new FileReader();
reader.onload = function(event) {
var csvdata = event.target.result;
parsed = d3.csvParse(csvdata);
};
reader.readAsText(file);
console.log(parsed)
};
I'm not sure if the file read is not finishing before the rest of the code executes but I was hoping .onload would stop that.