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.

3
  • 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. Commented Oct 17, 2014 at 1:01
  • 1
    papaparse.com Commented Oct 17, 2014 at 1:06
  • @JaredFarrish - what does that have to do with anything? This question is about accessing the file, not about parsing it. Commented Oct 17, 2014 at 1:18

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.