0

I am trying to supply a user-selected csv file through input type="file" and read it using JQuery's $.ajax() then display it to an empty html table. For some reason, it's unable to see the file that was selected by html's file chooser.

I'm stuck on this part and don't know how to get the path or whether or not I'd have to supply the path of x.csv file. I did some research and found about this.files[0]['mozFullPath'] but seems to be something applicable only when using Mozilla Firefox.

Is there any better or correct approach to what I'm trying to do?

$('#csv_file_input').on('change', function () {
    var fileInput = $('#csv_file_input')[0].files[0].name;
    console.log(fileInput);
    $.ajax({
        url: fileInput, //404 not found
        dataType: "text",
        success: function (data) {
            var employee_data = data.split(/\r?\n|\r/);
            var table_data = '<table class="table table-bordered table-striped">';
            for (var count = 0; count < employee_data.length; count++) {
                var cell_data = employee_data[count].split(",");
                table_data += '<tr>';
                for (var cell_count = 0; cell_count < cell_data.length; cell_count++) {
                    if (count === 0) {
                        table_data += '<th>' + cell_data[cell_count] + '</th>';
                    }
                    else {
                        table_data += '<td>' + cell_data[cell_count] + '</td>';
                    }
                }
                table_data += '</tr>';
            }
            table_data += '</table>';
            $('#data_preview').html(table_data);
        }
    });
});

I prefer to achieve this without using other libraries. I get 404 not found on the url part of $.ajax() block which I suspect to be because of selected file's path incorrectly read or path missing.

I'd appreciate any help or suggestion.

Thank you.

heisenberg
  • 1,784
  • 4
  • 33
  • 62

1 Answers1

0

I was able to solve it after doing research. I realized there's no need to use JQuery's $.ajax(). Below is my solution and I hope this will help others having the same problem who will see this question.

$('#csv_file_input').on('change', function (e) {
    var ext = $("#csv_file_input").val().split(".").pop().toLowerCase(); //csv
    if (e.target.files != undefined) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var csvval = e.target.result.split("\n");
            var jsonObj = [];
            var headers  = csvval[0].split(",");
            for(var i = 1; i <csvval.length; i++){
                var data = csvval[i].split(',');
                var obj = {};
                for(var j = 0; j < data.length; j++) {
                    obj[headers[j].trim()] = data[j].trim();
                }
                jsonObj.push(obj);
            }
            var jsonData = JSON.stringify(jsonObj);
            addDataToTable(jsonData);
        };
        reader.readAsText(e.target.files.item(0));
    }
    return false;
});

function addDataToTable(jsonObjArr){
    var json = JSON.parse(jsonObjArr);
    console.log(json);
    console.log(typeof json);
    var tbl = $("#data_preview");
    for(var i = 0; i < json.length-1; i++){
        var studentId = json[i]['studentId'];
        var firstName = json[i]['firstname'];
        var lastName = json[i]['lastname'];
        var middle = json[i]['middle'];
        tbl.append(
            "<tr><td>" + studentId + "</td>" +
            "<td>" + firstName + "</td>" +
            "<td>" + lastName + "</td>" +
            "<td>" + middle + "</td>" +
            "</tr>"
        );
    }
}
heisenberg
  • 1,784
  • 4
  • 33
  • 62