PapaParse returns undefined when reading CSV

My goal is to open the CSV file and then parse its contents on the <div> using PapaParse. While it works, but instead of the actual values, it returns undefined. I don’t know what happened, it could be a strange CSV file (I did this from an excel table using 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 tested ( http://www.topdeckandwreck.com/excel%20graphs/ ). I don’t know if this is really relevant, since the purpose of this is so that the user can open any CSV file, and then make a schedule out of it :)

+5
source share
3 answers

You probably have synchronization issues.

Dad is an asynchronous library, a signal sign is the fact that offers a complete callback.

This means that you cannot use a global variable to pass your results from A to B. In fact, you should avoid global variables at all.

All the work that you want to do 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); }); 
+10
source

I think you want to see the results when they really 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>"); } }); } 
0
source

ok, so I solved the problem, the solution is (var should contain results.data)

{

 function handleFileSelect(evt) { var file = evt.target.files[0]; Papa.parse(file, { complete: function (results) { var data = results.data; $(".graphcontainer").append("<div class='parse'>" + data + "</div>"); } }); } $(function () { $("#csv-file").change(handleFileSelect); }); 

}

thanks for the help from others

0
source

Source: https://habr.com/ru/post/1210250/


All Articles