1

I'm trying to do something fairly simple I think but I'm missing something. I've very new to Javascript. I'm trying to read a CSV file in to an array (in my code below I'm simply trying to output the data to an alert box). I keep getting an error "access denied."

function readTextFile(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, true);
  rawFile.onreadystatechange = function () {
    if(rawFile.readyState === 4) {
      if(rawFile.status === 200 || rawFile.status == 0) {
        var allText = rawFile.responseText;
        alert(allText);
      }
    }
  }
  rawFile.send(null);
}

I suspect there is an issue with where I have the csv file located? Due to restrictions with our CMS I can only reference the file like this www.example.com/csvfile.csv.

Any help would be greatly appreciated.

Weafs.py
  • 22,731
  • 9
  • 56
  • 78
user3766366
  • 67
  • 1
  • 3
  • 8
  • 1
    Is your `file` on the same domain as the web page you're requesting it from? If not then you may be seeing [same-origin security restrictions](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). – jfriend00 Oct 17 '14 at 01:01
  • 1
    http://papaparse.com/ – Jared Farrish Oct 17 '14 at 01:06
  • @JaredFarrish - what does that have to do with anything? This question is about accessing the file, not about parsing it. – jfriend00 Oct 17 '14 at 01:18

2 Answers2

6

Here is sample code for reading csv file into array

var request = new XMLHttpRequest();  
request.open("GET", url, false);   
request.send(null);  

var csvData = new Array();
var jsonObject = request.responseText.split(/\r?\n|\r/);
for (var i = 0; i < jsonObject.length; i++) {
  csvData.push(jsonObject[i].split(','));
}
// Retrived data from csv file content
console.log(csvData);

Here is the working fiddle example: http://jsfiddle.net/BdCnm/450/

selvarajmas
  • 1,623
  • 13
  • 20
0

Give this link a try and check his source code on Github, he lays it out in a pretty concise way.

https://github.com/MounirMesselmeni/html-fileapi

user3724235
  • 33
  • 2
  • 9