/    Sign up×
Community /Pin to ProfileBookmark

Load CSV or TXT file into javascript array

Hi guys, I am new at javascript and I want to know if it is possible to load either a CSV file or TXT file into an array. Basically the file gets downloaded from the net and is actually a txt file.

e.g. (“Heading 1″,”Heading 2″,”Heading 3”,”Heading 4″…. and under that is the details “Data 1″,”Data 2″,”Data 3”,”Data 4″….)

I can easily convert this to a CSV file too.
The web page will always display the data and that is all.

At the moment I have this code in my js file which I found on the net after searching for two days, this is the only way I know of at the moment. Is this OK and how do I move it into an array.

[code] var txtFile = new XMLHttpRequest();
txtFile.open(“GET”, “file://D:/Notices/notices.txt”, true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it’s found the file.
allText = txtFile.responseText;
lines = txtFile.responseText.split(“rn”); // Will separate each line into an array
} //”rn”
}
}[/code]

Am I going about this correctly? Is there an alternative to do this? I was going to display the information in a table. Bearing in mind that this is to be diplayed on a screen for people to read in a reception area. The text file itself will not have more than 100 lines (max). I will want the information to scroll on the screen but that is another problem for another day. I just need to find a way to display this text file on screen.

Thanks.

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERMar 05.2010 — Assuming the TXT (or CSV) file is loaded into the 'allText' (textarea?) correctly:

var allTextLines = [];

allTextLines = allText.split(/rn|n/);

Should create an array of all the lines from the text loaded

Then for each line to process:

var fldHeading = []

fldHeading = allTextLines[0].split(',');

Should create an array of the heading information and

var fldData = []

fldData = allTextLines[x].split(',');

Should create an array for each data field

where 'x' is the array position from 1..n

Depending upon what you want to populate (table? div? list?)

you should be able to create the display from the two arrays.

Note, you might need to do extra processing if the data fields contain a ',' separator WITHIN the field.

Good Luck!

?
Copy linkTweet thisAlerts:
@ComputerJoeMar 08.2010 — I am struggling with the same code set. I got the fso.OpenTextFile() method to work but cannot get XMLhttpRequest() working with file:// or with a http:// reference. Eventually I will need to index records but when I cannot even read a single line into a varible .

I'm hoping to pull a single record out of a table and display in a standardized form. Here is what I've got, what am I missing?

<script type="text/javascript">

var allText =[];

var allTextLines = [];

var Lines = [];

var txtFile = new XMLHttpRequest();

txtFile.open("GET", "file://c:/data.txt", true);

txtFile.onreadystatechange = function()

{

allText = txtFile.responseText}

allTextLines = allText.split(/rn|n/)

}

document.write(allTextLines);<br>

document.write(allText);<br>

document.write(txtFile);<br>

</script>
Copy linkTweet thisAlerts:
@JMRKERMar 08.2010 — Ajax code will ONLY work with files on a server. Cannot read local 'files'.

If you need to load local 'files', then you will need to change the extension to .js and put in valid javascript code.
Copy linkTweet thisAlerts:
@ComputerJoeMar 09.2010 — thanks

Someone said you could just replace http:// with file:// and PROTON's exampled referenced d:noticesnotices.txt so I tried it as well.

Found some more step by steps at CreativeCommons.org
Copy linkTweet thisAlerts:
@JMRKERMar 09.2010 — thanks

Someone said you could just replace http:// with file:// and PROTON's exampled referenced d:noticesnotices.txt so I tried it as well.

Found some more step by steps at CreativeCommons.org[/QUOTE]

So ... did it work? If it did, post some referenced as I've read that it is not possible elsewhere.
Copy linkTweet thisAlerts:
@protonauthorMar 09.2010 — So ... did it work? If it did, post some referenced as I've read that it is not possible elsewhere.[/QUOTE]


Damn I am having trouble reading the local file. I did get it to work once, but changed the code. I'll be going back and trying to replicate what I did.
Copy linkTweet thisAlerts:
@ComputerJoeMar 09.2010 — I've tried embedding the script in html and referencing server side and local data.txt and still have not received a response with my document.write statements.

you are further ahead than I.
Copy linkTweet thisAlerts:
@JMRKERMar 09.2010 — I think you guys are kicking a dead horse.

The only way to reference a local text file I know of is with ActiveX using MSIE. But this is a one browser solution. I still don't think javascript is able to do Ajax loads that are not from the server.

But ... let me know if you can prove me wrong ... it would be news for all.

?
Copy linkTweet thisAlerts:
@protonauthorMar 09.2010 — OK so far I can get the text to display on the page and this is the code I have at the moment. I am still testing this out.

[CODE]
var allText =[];
var allTextLines = [];
var Lines = [];
var txtFile = new XMLHttpRequest();

txtFile.open("GET", "file://D:/Notices/notices2.txt", true);
allText = txtFile.responseText;
//allTextLines = allText.split(/rn|n/);
//alert(allTextLines);
txtFile.onreadystatechange = function()
{
if (txtFile.readyState == 4)
{

// Makes sure it's found the file.
allText = txtFile.responseText;
allTextLines = allText.split(/rn|n/);

document.write(allText);
} else { //alert("Didn't work");
}

}
txtFile.send(null)[/CODE]


I don't have much time to play around with this, but I will try it this whole week when I have free time. Tell me what you get guys and if you can improve on this. Basically I am glad I got it to display on the page. Now I need to see if I can manipulate the data. And yes I have been reading that opening files in JS is really a no no because security issues. But I just want to display what is in the txt file on screen.
Copy linkTweet thisAlerts:
@DyngryMay 21.2013 — Hello,

I'm facing almost the same problem I want to load a CSV file and parsing it into an array to show it.

The problem is that I can't even download the file, each time the array stays empty.

Here is codes that I used : (The code cotted as a comment doesn't work as well)


[CODE]//function readCSV(locfile) {

// load a whole csv file, and then split it line by line
//var req = new XMLHttpRequest();
//req.open("GET",locfile,true);
//req.send();
//req.open("POST",locfile,false);
//req.send("");
//return req.responseText.split(/n/g);

//}
function readCSV(U,V) {
var csvRequest = new Request({
url:U,
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
alert ("Success");
}
}).send(); //Don't forget to send our request!
alert ("Test : "+response);
return response;

//var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
//X.open(V ? 'PUT' : 'GET', U, false );
//X.setRequestHeader('Content-Type', 'text/html')
//X.send(V ? V : '');
//return X.responseText.split(/n/g);
}
[/CODE]
Copy linkTweet thisAlerts:
@TcobbMay 21.2013 — Maybe I'm not understanding the exact why of it but it seems to me that you ought to be parsing the information files on the server and then spitting it out as a JSON structure. The javascript on the client side can just gulp it down with no processing needed. Use AJAX to call a program on the server that will produce the JSON from the csv or text file.
Copy linkTweet thisAlerts:
@RufusVSApr 16.2019 — @Dyngry#1268523 , Your jQuery selector is incorrect, to specify an element id, you need to prefix it with #, like this:

$("#csvResponse").value = response;

Also, returning the response value or alerting within the main function won't return anything of value

because the file would not have been read, until your success callback has been run.

But the correct jQuery should put the response in the value attribute of #csvResponse
×

Success!

Help @proton spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...