I could probably/def read a text file with javascript by embedding some ruby in there but I want to know how to do it with javascript. My code follows:

<HTML>
<HEAD>
<TITLE>"Text File"</TITLE>
<SCRIPT LANGUAGE = JAVASCRIPT>

function handleFile() {
    var myFile = document.getElementById('txtF')
	var fileContents = System.IO.File.ReadAllLines(myFile);
	
	document.form1.textfield.value=fileContents;
}

</SCRIPT>

</HEAD>

<BODY>

<input type="file" id="aFile" name="txtF"/>

<form name="form1">
<input type="text" name="textfield" value="">
</form>

<input type="button" value="Read File" onclick="handleFile();">
<!-- <button onclick="loadTxtDoc('textfile.txt')">Click</button>  //-->

</BODY>
</HTML>

what am I doing wrong?

I don't think you can read the file with javascript (but nevermind).
Your mistake:

var myFile = document.getElementById('txtF')
//this means: ID="txtF", and you don't have it (you have name="txtF")
//so, you have to replace it (name) with ID (or add id='txtF')

use jquery:

$(".content").load("file.html");
Member Avatar for tawes01

It's much easier to read an XML file, but if you really want to read a text file, I've done it before. I used this tutorial/guide, and it was very helpful.

oh ok, I didn't realize javascript was not a simple language to use to read text files... like in regular Java, it is SO easy to read a text file. what is this other way to read xml files then?

Member Avatar for tawes01

I'm not sure exactly how, but I know it's easier. It's still kind of complicated, though.
http://www.w3schools.com/xml/xml_parser.asp

Now, you should know that Javascript is not a file-manipulating language. In other words, it is not meant for, and is not really capable of (at least alone, without activex) reading external files. It can reference them, but not really access the content of those files and store it in a variable.

Yahoo Pipes has the ability to read the contents of file and assign them to a variable that can be invoked from client side javascript.

It's close cousin YQL also has 'storage pockets' 100kb in size that the contents of which can be manipulated by browser javascript in conjuntion with Yahoo Pipes.

However doing it this way is an ugly hack and should only be used as a last resort if the webhost does not support server side scripting. (it's not common but some don't believe it or not)

thanks! Yeah, I'll def check out YQL and Yahoo Pipes. And, thanks for that link about XML, I'll try that too.. I'll probably end up usingi a combo of these answers..

oh and Tawes, what do you mean that js can reference files, but not read them? cuz that might be enough..

Here is an old (pre using JQuery) script that reads in a .csv file to make a table out of it - from a forum question a long long time ago. The XML route would be much easier to format and maintain in the long run.

It's similar to the tutorial - but uses the XMLHttpRequest to bring in the text. At least it gives another option to think about.

// JavaScript Document
// Thank you VERY much to Ben Nadel for this on his blog
// posted at 
//http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
	

if (window.XMLHttpRequest) {
		//for firefox, opera and safari browswers
		var txtFile = new XMLHttpRequest();
	}
	if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP.3.0 and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");
  };
  
txtFile.open("GET","TestingOne.csv");
txtFile.send(false);

var allText = txtFile.responseText;

	
function clickyHere (){
	//var tar = document.getElementById('finalTable');
	var info = txtFile.responseText;
	var infoArray = [];
	infoArray = info.split(/,|,+\s|\s+,\n|\r/);
	var tableCount = info.split(/,|\$/g).length;
	var rowCount = info.split(/\r|[\r]/g).length;
	var endLine = info.split(/\$/g).length;
	var columnTry = tableCount/endLine;
	document.write("<table border='1' columns='"+columnTry+"'>");
	document.write("<tr>");
	var count;
	count = 0;
	for (i=0;i<infoArray.length;i++){
		x = infoArray[i];
		document.write("<td>"+x+"&nbsp;");
		if (count != columnTry){
			count ++;
			//document.write("</td>");
			}
		if (count >= columnTry){
			document.write("</tr><tr>");
			count = 0;
			}
	}					
			document.write("</tr></table>");
			
}

The Html code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="tableTest3.js"></script>
<title>Untitled Document</title>
</head>

<body>
<form id="tablebuild">
<input type="button" value="Click me" onclick="clickyHere();" />
</form>
<div id="finalTable"></div>
</body>
</html>

I attached the original text file, but I did convert it to a csv file.

Thanks so Much! that is exactly what I am trying to do! I am trying to make a list on my webpage based on a CSV file I get updated versions of every so often...

Only problem is, the 'FileSystemObjects' from Tawes do not seem to work properly on my Linux Ubuntu machine.


And Macgurl70, that code is great! Looks like it does exactly what I need the code to do... but the table (that is generated after pushing the button) is blank.. and I read the text file, it is DEFINITELY not blank... does this also not work on linux?

oh... wow, nvm.. I am very dumb :D all I had to do was change the name of the list file from, 'TestingOne.txt' to 'TestingOne.csv'...

Wow, sorry about that! I am kinda special I guess :\

Thanks again for the code!

macgurl70,
I would change this
txtFile.send(false);
like so:
txtFile.send(null);

This is great except that the CSV data will come out as unquoted so when i run something like indexOf(7) it cannot read strings.
what can you add to that RegEx so that the items are "quoted"

thanks.

thanks stbuchok but the reason why i'm looking at this javascript solution is because i have to be compatible with IE 7.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.