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);
});
2
  • 2
    Read this: stackoverflow.com/questions/14220321/… Commented Nov 14, 2014 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. Commented Nov 14, 2014 at 15:50

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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!
i guess, the varaible isn't called CSV then. try replacing it with $.csv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.