Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript loading CSV file into an array

I am developing a web page in Wordpress. The webpage needs to have a combobox with all counties. I have a dataset in csv format which has some 10k rows for all these counties. When the user selects a county in the dropdown, I want only the selected county data displayed in the web page. This is my requirement.

In wordpress, my web page I am adding the js file using

<script type="text/javascript" src="http://xxx/wp     content/uploads/2014/05/countyList1.js"></script>

and the code for webpage dropdown is

<select name="county" id="county" onload="setCounties();" onchange="getSelectedCountyData();"></select>

In countyList1.js file I have the setCounties() and getSelectedCountyData() functions.

So far I can see the dropdown with counties list. I don't know how to read the CSV file and apply the selected county filter to this list.

I tried the FileReader object and I can load the CSV contents on the web page but I don't want the user to select the CSV. I have the dataset already.

I am trying to use this jquery.csv-0.71 library from this SO post How to read data From *.CSV file using javascript? but I need help.

Here's the code which gets called when a county is selected

function getSelectedCountyData() {
        cntrySel = document.getElementById('county');
        //selCty = countyList[cntrySel.value];
        handleFiles();
}

function handleFiles() {

    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "D:\Docs\Desktop\csvfile.csv",
            dataType: "csv",
            success: function (data) { processData(data); }
        });
    });
}

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    var lines = [];

    for (var i = 1; i < allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = [];
            for (var j = 0; j < headers.length; j++) {
                tarr.push(headers[j] + ":" + data[j]);
            }
            lines.push(tarr);
        }
    }
    console.log(lines);
    drawOutput(lines);
}

function drawOutput(lines) {
    //Clear previous data
    document.getElementById("output").innerHTML = "";
    var table = document.createElement("table");
    for (var i = 0; i < lines.length; i++) {
        var row = table.insertRow(-1);
        for (var j = 0; j < lines[i].length; j++) {
            var firstNameCell = row.insertCell(-1);
            firstNameCell.appendChild(document.createTextNode(lines[i][j]));
        }
    }
    document.getElementById("output").appendChild(table);
}
like image 895
Aqua267 Avatar asked May 20 '14 14:05

Aqua267


People also ask

How do I import a CSV file into JavaScript?

Papa. parse("http://example.com/bigfoo.csv", { download: true, step: function(row) { console. log("Row:", row. data); }, complete: function() { console.

How do you turn a string into an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can you add to an array in JavaScript?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().


1 Answers

You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.

Use the FileReader API:

<input type="file" id="file input">

js:

console.log(document.getElementById("file input").files); // list of File objects

var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);

Then parse content as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""

like image 65
Halcyon Avatar answered Sep 30 '22 21:09

Halcyon