Currently, I am developing a small web application that requires the user to upload a .csv file, which is then parsed into an array using JavaScript. However, I have encountered an issue where the JavaScript code only functions properly when I have developer tools open (in Firefox or Chrome) and a breakpoint set in the code. Strangely, the breakpoint can be on any line of code, and the file is read and parsed successfully. However, without the breakpoint, the JavaScript runs to completion, but the 'parsed' variable remains empty. It's only when I set a breakpoint and step through the code that my test data is parsed into an array as expected.
For parsing the data, I am using d3 library as I plan to use it for generating graphs in the future.
Here is the HTML code:
<!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="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4822393d2d3a31087a6679667b">[email protected]</a>" 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>
And here is the JavaScript code:
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 suspect that the file reading process might not be completing before the rest of the code executes, even though I expected the .onload event to prevent that.