Reputation: 11
I am trying to import CSV data from a CSV file using Javascript. I wrote the code and I don't know what the problem is. When I upload the HTML page to my website it does not work and the script kinda crashes. I tried multiple ways but none worked. Here is the code:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "files/testfile.csv",
dataType: "text",
data: {
html: 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 = 0; 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);
}
}
alert(lines);
}
Help is much appreciated
Upvotes: 1
Views: 6410
Reputation: 13796
Try this instead:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "files/testfile.csv",
dataType: "text",
success: function(data) {
processData(data); //define your own function
}
});
});
If it's still not working, check your browser console for errors. You might also try putting some console.log() lines in there to see what's going on.
Upvotes: 3