0

I am trying to load data from an csv file to an html file and I want to have it displayed in a table.

My idea was to open the csv data and split it with this code in table rows and and then the cells for the rows.

This is my code so far. Maybe you can help me with what's wrong? I am thankful for any idea!


<body>
    <script src="jquery.min.js"></script>
    <script>
        function readCsv(data) {
            var allRows = data.split(/\r?\n|\r/);
            var table = "<table>";
            for (var singleRow = 0; singleRow < allRows - length; singleRow++) {
                if (singleRow === 0) {
                    table += "<thead>";
                    table += "<tr>";
                } else {
                    table += "<tr>";
                }
                var rowCells = allRows[singleRow].split(',');
                for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
                    if (singleRow === 0) {
                        table += "<th>";
                        table += rowCells[rowCell];
                        table += "</th>";
                    } else {
                        table += "<td>";
                        table += rowCells[rowCell];
                        table += "</td>";
                    }

                    if (singleRow === 0) {
                        table += "</tr>";
                        table += "</thead>";
                        table += "<tbody>";
                    } else {
                        table += "</tr>";
                    }
                }
                table += "</tbody>";
                table += "</table>";
                $("body").append(table);
            }
            $.ajax({
                url: "world_data_v1.csv",
                dataType: "text"
            }).done(readCsv);
        }

    </script>
</body>
</html>


  • 1
    Possible duplicate of [How to read data From \*.CSV file using javascript?](https://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript) – Gurupad Hegde Oct 28 '19 at 08:07

1 Answers1

0

Your $.ajax should be outside readCsv and inside a $(document).(ready)