My goal is to open a CSV file, then parse its contents onto a <div>
using PapaParse. So far it seems to be working but instead of actual values it just returns undefined. I have no idea what's wrong, could be a strange CSV file (I made this from an excel table with Save As), or it could just be sloppy coding.
JS
var data;
function handleFileSelect(evt) {
var file = evt.target.files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
complete: function (results) {
data = results;
}
});
$(".graphcontainer").append("<div class='parse'>" + data + "</div>");
}
$(document).ready(function () {
$("#csv-file").change(handleFileSelect);
});
HTML
<div class="graphcontainer">Parser Output:</div>
<div class="buttoncontainer">
<input type="file" id="csv-file" name="files"/>
</div>
edit: here are the files I've been testing with (http://www.topdeckandwreck.com/excel%20graphs/). Don't know if this is really relevant as the goal of this is for the user to be able to open any CSV file and then making a graph out of it :)
You very likely have a timing problem.
Papa is an asynchronous library, a telltale sign is the fact that is offers a complete
callback.
That means you can't use a global variable to transfer its results from A to B. In fact, you should avoid global variables in general.
All work you want to be done after the result is ready must be done in the callback function. This applies to any asynchronous process in JavaScript.
function handleFileSelect(evt) {
if ( !(evt.target && evt.target.files && evt.target.files[0]) ) {
return;
}
Papa.parse(evt.target.files[0], {
header: true,
dynamicTyping: true,
complete: function (results) {
debugDataset(results);
renderDataset(results);
}
});
}
function debugDataset(dataset) {
var formatted = JSON.stringify(dataset, null, 2);
$("<div class='parse'></div>").text(formatted).appendTo(".graphcontainer");
}
function renderDataset(dataset) {
// render code here...
}
$(function () {
$("#csv-file").change(handleFileSelect);
});
I think you want to see the results when it's actually completed:
function handleFileSelect(evt) {
var file = evt.target.files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
complete: function (results) {
var data = results;
$(".graphcontainer").append("<div class='parse'>" + data + "</div>");
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With