Jace YJ Jace YJ - 1 month ago 11
Javascript Question

jquery function can not be defined even though it is imported

I am using Evan plaice jquery-csv libary but I am running into a lot of trouble to get it working at the moment due to his code not updated after google code is deprecated.

I am using the one of his example where you upload a csv file and it will parse the document so that the csv file will be shown on the webpage Demo here.

I downloaded his code from github but then since the googlecode he imported is not working anymore I put the file jquery.csv.js in the same folder as the file I am using. In the jquery.csv.js, there is a function being called which is toArray in the html file. I deleted the line where it is used to be

<script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script>
and added
<script type="text/javascript" src="./jquery.csv.js"></script>
However, for whatever reason it complains that toArry is not defined.

Basically the code is like this:

function printTable(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv); << The line that has problem.
var html = '';
for(var row in data) {
html += '<tr>\r\n';
for(var item in data[row]) {
html += '<td>' + data[row][item] + '</td>\r\n';
}
html += '</tr>\r\n';
}
$('#contents').html(html);
};
reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
}


In the developer console it indicates:


Uncaught TypeError: Cannot read property 'toArrays' of undefined
at FileReader.reader.onload (file:///Users/Jace/Downloads/jquery-csv-master/examples/file-handling.html:75:25)

Answer

I think you're problem is that when you removed the reference to the jquery-csv library hosted on Google Code and included your local version, you put it above the reference to jQuery itself. That's when I notice the error you're describing. The order you load in your JavaScript files does matter. When for example JavaScript code in file B.js is depending on code in A.js, A.js needs to be specified before B.js.

So basically check if the order you're specifying the files in in your HTML file is correct:

<body>
    <!-- HTML... -->

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="jquery.csv.js"></script> <!-- The "./" is not used here -->

    <script>
        // Code...
    </script>
</body>

Also, the ./ in front is not needed and not common. I've never used it in any case. ;)

I hope that makes it a bit more clear to you!