javascriptjquerycsvjquery-csv

ReferenceError: CSV is not defined


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);
});

Solution

  • 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);