jz8888
jz8888

Reputation: 13

"Uncaught TypeError: csv.replace is not a function" when using csv jquery plugin, how do I fix this?

In the following code:

  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "file://csvFileName.csv", true);
  console.log(rawFile);
  var input = $.csv.toObjects(rawFile);
  console.log(input);

I'm trying to convert a .csv file into a readable file, and then I'm trying to run a .toObjects command on it to produce a csv file that's easier to work with, but I keep running into an "Uncaught TypeError: csv.replace is not a function" error on the fourth line. I'm using the most upvoted answer to this question as a basis.

I've read through the documentation but I can't seem to find a particular answer to this error, does anyone know of a fix?

edit: this isn't my entire code, I have a script link to the jquery plugin in my html header. This is just the section where the error is. link looks like:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>

Upvotes: 1

Views: 1971

Answers (3)

Khauri
Khauri

Reputation: 3863

First thing's first, you're not using XMLHttpRequest right. Reference this site to see how to use it. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Secondly, you can't do this without a web server to host your csv file. The file:// protocol isn't supported with XMLHttpRequest. There's tons of ways to set up a webserver, but a quick an easy way is to use this chrome extension.. Then edit the url of your file to be relative to your js file. (The same way you'd include css in html).

You could also use the Fetch API like someone else commented, but some browsers (mainly Internet Explorer) don't support it, so keep that in mind.

var rawFile = new XMLHttpRequest();
  rawFile.addEventListener("load", reqListener);
  rawFile.open("GET", "/csvFileName.csv", true);
  rawFile.send();
  function reqListener(){
    var csvText = this.responseText;
    console.log(csvText);
  }

Upvotes: 0

shmulik friedman
shmulik friedman

Reputation: 195

XMLHttpRequest is not a file, you should do a request either with XMLHttpRequest's open function, or see bellow, after that you should get the file out the response data. you can use instead:

fetch("file://csvFileName.csv").then(function(resp) {
    return resp.blob();
}).then(function(blob) {
    var file = new File([blob], "name");
    var input = $.csv.toObjects(rawFile);
    console.log(input);
});

Upvotes: 0

Barmar
Barmar

Reputation: 781974

You need to send the AJAX request, and call $.csv.toObjects() in the callback function. Its argument needs to be the string from the AJAX response.

var rawFile = new XMLHttpRequest();
rawFile.open("GET", "file://csvFileName.csv", true);
rawFile.onload = function() {
    var input = $.csv.toObjects(this.responseText);
    console.log(input);
};

Upvotes: 1

Related Questions