mcplums
mcplums

Reputation: 259

Get CSV into array using jquery-csv

I am trying to get data from the following CSV which is in my local folder as bids.csv:

1, 3000
4, 2500
15, 2000

into an array. I'm using the jquery-csv library but without success.

Here is my entire code:

<html><head>
  <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
  <script src="jquery-csv.js"></script>
</head>
<body>
  <script type="text/javascript">
  data = $.csv.toArray('bids.csv');
  console.log(data)
  </script>
</body></html>

When I go to JS console in chrome, there is indeed an array in the console, but it seems to not have my data that I was looking for, instead a huge amount of guff. I can only assume this is the default array that jquery-csv outputs and that it is not reading my csv for some reason.

Upvotes: 3

Views: 14555

Answers (2)

Mehdi
Mehdi

Reputation: 7403

This problem happens because you first need to retrieve the CSV file, then only pass it to jQuery-csv plugin.

As per the plugin documentation:

$.csv.toArray(csv);

[...]

csv (required) The csv data to be transformed.

The code shared in your question considers bids.csvto be the CSV data.

Assuming the file is accessible from a server (localhost works):

One way to retrieve the CSV data is to emit an Ajax GET request, jQuery's has a feature built-in for this: jQuery.get.

The solution would then be:

<html><head>
  <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
  <script src="jquery-csv.js"></script>
</head>
<body>
  <script type="text/javascript">
  // sent a GET request to retrieve the CSV file contents
  $.get( "bids.csv", function( CSVdata) {
     // CSVdata is populated with the file contents...
     // ...ready to be converted into an Array
      data = $.csv.toArray(CSVdata);
      console.log(data)
  });
  </script>
</body></html>

It is left as an exercise to the reader to manage errors which may happen either during the file retrieval, or during the conversion.

If you don't want to carry the somewhat heavy jQuery library, other libraries you may want to look at are:

Upvotes: 3

Sreeraj
Sreeraj

Reputation: 21

I can see that you added the file name to the array. You need to read the file using FileReader and then use the toArrays() function.

You can see the example here

Upvotes: 0

Related Questions