Seb
Seb

Reputation: 31

CSV file to Varible struggling, using papa.parse

Ok, the goal is to copy the CSV from a file and store them as a string in javascript.

Using Papaparse I have managed to get the contents from the CSV file but I cant seem to save the string outside of papaparse to use in another script.

I have very new to javascript so be kind :)

the while loop is to adjust the format to how i need it, however if i can get the data out i can do this outside of where it currently sits. Any help is welcome as this is driving me nuts! many thanks!! :D

<title>Test stuff</title>
<script src="./Plugins/papaparse.js"></script>
</head>
<body>
<p id="demo"></p>
<script>
Papa.parse("http://test_server/OpenSiteVisitTickets.csv", {
download: true,
complete: function(results) {
console.log("Remote file parsed!", results);
    var i= 0, x= [1],cname= [1],postc= [5],alenth = results.data.length -2;
        locations= [];
        while ( i < alenth )
            {
            var ltemp =[];

            ltemp = "[" + results.data[x] [cname] +", "+results.data[x] [postc] +"] ";
                locations = locations.concat(ltemp);
            i++,x++;
            }
    document.getElementById("demo").innerHTML = locations;
     }
    });
 </script>
 <script>
  // other script goes here and picks up locations var todo its funky shiz :)
 </script>

 </body>
 </html>

Upvotes: 1

Views: 1362

Answers (1)

Seb
Seb

Reputation: 31

Thanks Matt for your answer; and thanks Nepeo for you advise on globals;

Well parsing a file over the network is asynchronous so any results you get won't be available until after the complete function is executed. The "other script goes here" needs to wait until that complete callback is fired; or more likely, the complete callback has to invoke that code. – Matt 2 days ago

A cleaner way of creating a global variable is to use window.locations = ... or even better is to just write the var locations; at the top of the file and set it in the callback. @Matt is right that your probably suffering from async agony though! – nepeo 2 days ago

Upvotes: 2

Related Questions