Load text file from site files - javascript

I need to load a text file in js, the text file is in the same dir as the .js file.
I found this code
var file = new XMLHttpRequest()
file.open("GET", "file.txt", true)
file.send()
file.onreadystatechange = function () {
if (file.readyState == 4 && file.status == 200) {
console.log(file.responseText)
}
}
But that doesn't work if I open my site locally ("file:///C:/site.html")
How can I load a text if it is run locally? (Without using JQuery)
EDIT
I do not want to use JQuery but these are some questions with using JQuery.
"Ajax in Jquery does not work from local file"
or
"Jquery load() only working in firefox?"

The security policies of web browsers disallow getting file resources. You can, however, use JSONP to circumvent this:
var tag = document.createElement("script");
tag.src = 'filename.txt';
document.getElementsByTagName("head")[0].appendChild(tag);
function callback (data) {
}
You'll need filename.txt to look something like this:
callback('<text-file-content>')

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.

How can I set the http RequestHeader for a file load in the $script.js library?

The $script.js library I am using
https://github.com/ded/script.js/
has the following Javascript. What I need to do is set the request header in this code block but I am not sure how to do this:
var el = doc.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
return false;
}
el.onload = el.onreadystatechange = null;
loaded = true;
// done!
};
el.async = true;
el.src = path;
document.getElementsByTagName('head')[0].insertBefore(el, head.firstChild);
Here's an example of something similar (not part of $script.js) that does set the request header:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
The first code block (the one I need to use but can modify slightly) is not very clear to me. Does anyone know how I can change this first code blocks (used in $script.js) to set the request header?
If I'm interpreting the library correctly, XMLHttpRequest isn't used directly by $script.js. It appears to be creating <script></script> tags dynamically and letting the browser handle downloading the script files. Using this library, it does not appear you can specify custom headers.
Altering the request headers the browser sends via Javascript is not possible according to some of the articles I've read including the answer to this question on SO: Is it possible to alter http request's header using javascript?
If you want to set custom headers, you'll need to use a dynamic loading library which uses XHR to load the scripts. Here is another article I've found with patterns for this type of functionality: On-Demand Javascript.

Javascript: can't load JSON file from localhost

I'm currently working through the book "Head first HTML5 programming". I want to load the content of a file named sales.json from a web server on my own machine. I used wampserver for this.
In the folder wamp/www/gumball/ I put all relevant .html, .js and .css files, and also the sales.json file.
My JavaScript code is very simple:
window.onload = function() {
var url = "http://localhost/gumball/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
This doesn't do anything! Typing the link: http://localhost/gumball/sales.json in my browser opens the right file, so the link should be correct. Even when using the .js files that come with the book (with a finished version of the application I'm trying to make), nothing loads.
Testing with alert statements tells me the request.onload event never happens. I'm clueless as to why this is the case.
A fact I don't quite understand yet: when I type: http://localhost/gumball/sales.json: in my browser (I added a colon at the end of the link), I get a 403 Forbidden error! Why does this happen? Does this have something to do with my problem?
I open html document with firefox
Your HTML document must be open with a URL in http://, not file://, if you want it to be able to open in javascript another document, unless the second document is served with relevant CORS headers.
This is due to same origin policy.
As you have a local WAMP server, there is no problem : simply open your file using a http:// URL like you do for your JSON file.

loading js files dynamically via another js file?

is there anyway to load other JS files from within a single JS file. I would like to point my individual pages "ITS" js file and that js file would load jquery, other js files.
I know i can just pop all these into the html i.e.
I was thinking of separations of concerns so i was wondering if anything exists already without me reinventing the wheel....
That i would just need to edit home.js to change what other js (jquery etc) are loaded for home.htm ... home.htm would just point to home.js
Thanks
You can take a look at dynamic script loading. Here's an excerpt from the article:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'helper.js';
head.appendChild(script);
For external domain JS link
var loadJs = function(jsPath) {
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', jsPath);
document.getElementsByTagName('head')[0].appendChild(s);
};
loadJs('http://other.com/other.js');
For same domain JS link (Using jQuery)
var getScript = function(jsPath, callback) {
$.ajax({
dataType:'script',
async:false,
cache:true,
url:jsPath,
success:function(response) {
if (callback && typeof callback == 'function') callback();
}
});
};
getScript('js/other.js', function() { functionFromOther(); });
This is similar to Darin's solution, except it doesn't make any variables.
document.getElementsByTagName('head')[0].appendChild(document.createElement("script")).src = "helper.js";
I'd suggest you take a look at labJS. It's a library made specifically to load Javascript. As they say..."The core purpose of LABjs is to be an all-purpose, on-demand JavaScript loader, capable of loading any JavaScript resource, from any location, into any page, at any time."
See the labJS home page for more information.
Google offers centrally hosted versions of the major javascript libraries like jQuery. They can be dynamically loaded using the google loader.
http://code.google.com/apis/ajaxlibs/documentation/

Categories

Resources