javascript function for reading multiple txt files for webpage - javascript

my company has tasked me with maintaning an internal environment webpage that houses the installers for each of our environments. the format of this location is: Root > webpage.html / EnvFolders > installer.exe / version.txt
the webpage has each environment listed, along with a static link to the sub folder installer file. it also has a line for the version. when we update an environment, neither the installer or version file names change, so the link to the installer never gets out of date. the version is supposed to be manually updated, but most of the time the tech doing the update doesn't, ergo, this post.
i am needing a way to read the single line within the version.txt file and display it in on the correct env. i am looking to have a line of code at each environment listing that then triggers a single function that does the actual work of pulling the data.
i've found this solution which works for a single file, but i need the function to iterate multiple times though different files. i've included the code below that works for a single file.
<span id="placeholder"></span>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('placeholder').innerHTML = xhr.responseText;
}
}
xhr.open('GET', 'test.txt');
xhr.send();
</script>

Related

How to read text file from filesystem in JavaScript

I have tried different approaches to read a text file from the local file system in JavaScript and display the content of the file in alert() but all to no avail.
Approach 1
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file , false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.response;
document.getElementById("content").innerText = allText;
alert(allText);
}
} else {
alert("Can't read the file");
}
}
rawFile.send(null);
}
readTextFile("FormulaQuestion.txt");
The FormulaQuestion.txt file is in the same directory with the html file, this approach shows an empty alert window on the browser
Approach 2 using fetch method
fetch('FormulaQuestion.txt')
.then(response => response.text())
.then((data) => {
alert(data);
})
This doesn't show anything
Approach 3 using JQuery
$.get('FormulaQuestion.txt', function (data) {
alert(data)
}, 'text');
This doesn't work either.
I am building a desktop application that uses a web browser control to load html file which is embedded into the application. The application reads the string from sqlite database and save it in the FormulaQuestion.txt file, then refreshes the WebControl component which reloads the html file.
Now when the html file is reloaded, the JavaScript should read the text file and display it on alert() which once the alert is able to display the file content, i will then set it to a paragraph and remove the alert().
Please someone should help me out.
Browsers by design do not allow access to the file system for JavaScript, as allowing such access would be a serious security concern.
To provide the FormulaQuestion.txt file to your script you will need to host the file on a server and request it via a HTTP request (like with your fetch). The key thing here is that a server is needed to actually transmit the file over the HTTP protocol to your script.
If working locally, there are many options for running a local server.
The npm serve module,
Wamp
Apache
You may also want to try out some free tier services like Vercel or Netlify. Both I believe allow you to just drag/drop a file and it will host it for you.

Fail to load .php files with ajax in Javascript

Instead of using jQuery here I am trying to use Javascript to load several .php files to
display data from the database according to the user's input. Below is an example of how my functions are like (and most of which are similar):
let userinput = document.getElementById("input");
button_1.onclick = function()
{
let xhr = new XMLHttpRequest();
xhr.open("GET", "ajax/highscore.php?q="+userinput.value, true);
// send the "username" to $_POST['q'] defined in "highscore.php"
// and then display the data according to the user's input
xhr.addEventListener("load", (event) =>
{
if (xhr.readyState == 4 && xhr.status == 200) { // display data accordingly }
});
xhr.send();
}
and below is a screenshot of the index in the server. "sample.html" is the page for displaying all the data.
However, when inspecting "sample.html", I cannot see the "ajax" folder loaded, nor any other .php files even when I changed the path "ajax/( ).php" to "( ).php". Could anyone explain why this will happen? (In the second screenshot because the parent folder contain my server's name so I covered it)
The browser dev tools (the inspect method you are using) do not list files in your server folder. It only displays files used to load your sample.html page, like CSS, JS files directly referenced (with <script> tags, and so on), etc.
Your .php files might still work, if your javascript ajax method calls them accordingly and they are reachable by the user's browser.

Open local server file using plain javascript

I want to load locally stored data using plain javascript (no jquery for example) and then use it to display it in a table in html. My project structure looks like this:
root
- js
-- main.js
- res
-- data.csv
- index.html
I tried using a XMLHttpRequest, but somehow I get status 0 when trying to load the file and when printing the response text it prints out nothing at all.
The following method is called using window.onload:
var url = "file://../res/data.csv/";
varxmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
I don't think you can access the file system through most browsers.
Even if it worked locally, it wouldn't work as soon as you put your page up on a server. This is because the client will be asking for a file that is local to itself, not the server.
Chrome may have something for you though:
https://www.html5rocks.com/en/tutorials/file/filesystem/

How to Load a local .JSON file in .js file

Issue
Unable to load local JSON file in a javascript file which is spun up with node.
Details
The question is straight forward but I am not serving the javascript file in a browser. I have a javascript file which has the logic, I then spin it up with:
node main.js
I googled a few solutions, they recommend using JQuery or XMLHttpRequest but they appear to be running into issues related to the fact i am no serving this in a browser.
Project Background
I am using a raspberry PI to get data from an IR Temperature Sensor. I am using python to get calculate the voltage, convert to celsius, then export that as a JSON file. I then plan to load this file into my javascript file which then configures angular fire Database and pushes this data.
I have a front-end application that will then pull this down and display the end data to the user.
If I go with the JQuery:
Option 1
sample:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
Error
$.getJSON is not a function even though I am requiring jQuery.
Option 2
If I go with pure javascript, I see
sample
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
Error
xobj.overrideMimeType is not a function
TL/DR
How do I load a local JSON file into a javascript file that is not loaded into a browser but instead spun up with node,
node main.js
Node.js can load JSON files through require. See the documentation here: https://nodejs.org/api/modules.html#modules_all_together
If filename begins with './' or '/' or '../'
If filename.json is a file, parse filename.json to a JavaScript Object. STOP
Most likely what you want is const json = require('./test.json') assuming test.json is in the same directory as the code requiring it. Remember that require parses the JSON, so json in the example is a JavaScript Object.

Request plain text file in javascript from URL?

I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work

Categories

Resources