Overview: I have been looking into ways of reading in a textfile without the need of filereader. I have a file called temp.txt located at "/temp.txt" (absolute path) and I have been using the following javascript function to try to read and print out the text located inside the txt file.
function readTextFile(file){
alert("Debug 1");
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);
alert("Nothing");
}
I use a button that calls the function onclick like so:
<button onclick="readTextFile('file:///temp.txt')">read the txt</button>
The Problem: When I click the button nothing happens. I have tried putting "file:///temp.txt" directly into my browser and the browser manages to correctly open the text file. Am I implementing the javascript wrong? I have tested this in Chrome. Thank you so much in advance!
Update 1: I have fixed some bugs on my code and have gotten the code to run the alerts, but when its supposed to print out the textfile in the alert(alert(allText);) it prints out nothing.
Sources: Javascript - read local text file
You can try the code here: https://jsbin.com/mucosavage/edit?html,output
just change the "/temp.txt" to something you have <button onclick="readTextFile('file:///temp.txt')">read the txt</button>