1

I am using the jquery.csv-0.71.min.js lib to load a csv file and convert it to an array. However, when loading my webpage:

<script src="assets/lib/jquery/dist/jquery.min.js"></script>
<script src="assets/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Jquery-csv -->
<script src="assets/js/jquery.csv-0.71.min.js"></script>
<script>
(function() {
            var data; 
            var url = 'data/data.csv';
            function makeRequest(url) {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                xhr.onload = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {/*run code*/}
                };
                xhr.send(null);
            }
        })();

        data = CSV.toArrays(xhr.responseText);
        console.log(data);
</script>

I get in the console:

ReferenceError: CSV is not defined at 'data = CSV.toArrays(xhr.responseText);'

Any recommendations what I am doing wrong?

I appreciate your replies!

UPDATE

I put my code into the document read funciton, however, I still get the same error as above.

$(document).ready(function() {
    (function() {
        var data;
        var url = 'data/data.csv';
        function makeRequest(url) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.onload = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {/*run code*/
                }
            };
            xhr.send(null);
        }
    })();

    data = CSV.toArrays(xhr.responseText);
    console.log(data);
});
Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • 2
    Read this: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – epascarello Nov 14 '14 at 15:19
  • I've used this lib in the past, but for dealing with simple CSV's it's easier just to parse it yourself. Incidentally in your example CSV.toArrays() should be in xhr.onload, it will execute before the XML has been read. – nepeo Nov 14 '14 at 15:50

1 Answers1

2

You code is executed before browser loads the CSV script. Wrap you JavaScript code with

$( document ).ready(function() {
  // PUT YOUR JavaScript CODE HERE
});

This will make browser to wait, until all your scripts are loaded, and only after to execute the code.

You can check the documentation of the jquery csv here. It says that you should invoke methods like this:

$.csv.toArrays(csv);
Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
Igor Milla
  • 2,767
  • 4
  • 36
  • 44
  • Thx for your answer! I tried to put my code into the `.ready( function()..` and I still get the same error as before. Please have a look at my update! – Carol.Kar Nov 14 '14 at 15:23
  • i guess, the varaible isn't called CSV then. try replacing it with `$.csv` – Igor Milla Nov 14 '14 at 15:28