Javascript read and display content of a file - javascript

I want to read a file that's saved in the same folder. Then I want to show its content in a div in index.html. The problem: when I used require("fs") it didn't work since it wasn't running server-side. I have been looking around and can't find a simple answer. I want to make my website a little dynamic, so here is the code that should fire upon a button click:
function videos() {
var body = *read a file("insertfilename")*;
console.log(body);
document.getElementById("body").innerHTML = body;
}
"body" in this case is just the id I gave the div.
!EDIT!
Now to explain it further. I want to use it as my main website. When I go onto there it should open an empty html file, which has a scriptfile as source. "onload" it should read a file , which is also already on the server, and put its content into a div inside of the body. If I click on a hotlink or a Button, it should read another file and put that content into that div instead. Maybe that gives a little clarification on what I am trying to do. I dont want to reload to open other sites of mine.

Seems like you need some basic file fetching since you are not using a server. Have you tried FileReader for javascript? It is a very simple and straightforward object. The example on the page seems similar to what you are trying to accomplish, except you want to fetch the file, not the user.

You can use AJAX. It stands for Asynchronous JavaScript And XML. You can send asynchronous requests to server with it. Just make sure that file that you are requesting is on the same domain as JS file.
function videos() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() { //this will execute when you receive response from the server
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML = this.responseText;
console.log(this.responseText)
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
}
Here is W3schools tutorial if you want to learn more.

Related

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/

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

XHR loading resources from separate directory

I have a simple XHR to load 'testdirectory/testpage.html'
var xhr; (XMLHttpRequest) ? xhr= new XMLHttpRequest() : xhr= new ActiveXObject("Microsoft.XMLHTTP");
xhr.onload = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var preview = xhr.responseText;
document.getElementById("content").innerHTML = preview;
}
}
xhr.open("GET", "testdirectory/testpage.html", true);
xhr.send();
I have it set up to display on button click. Works great.
Let's say testpage.html looks like this:
<h1>Loaded Page Heading!</h1>
<img src="main.png">
It will load but the image that is displaying is not main.png from that directory, it is main.png from the directory of the page that placed the XHR.
Is there a way to get the returned HTML to point to the 'testdirectory/main.png' image and not just use the current directory from the XHR? I'm looking for an alternative to changing the HTML of the page retrieved since that would defeat the purpose of what I'm trying to do.
I've been searching through StackOverflow for about 20 minutes, and I've googled a couple of different things. It seems like a question that must have been asked sometime before but is difficult to phrase/find.
I'm afraid you won't be able to achieve what you want without changing the retrieved HTML.
The xhr.responseText you receive from the XHR request is a string of HTML. When you do:
document.getElementById("content").innerHTML = preview;
you're taking that string of HTML and assigning it to the innerHTML property of that element. The innerHTML property parses that string of HTML and assigns the resulting nodes as children of the element. Any URLs in that parsed HTML will use the current document's base URL.
So basically, all you did was take some HTML string, parse it and append it to the current document. The innerHTML property doesn't care or know from where you obtained that HTML. The resulting nodes will behave exactly as any other HTML in the rest of the document.
It seems to me you're expecting the behavior of an iframe. But that's a totally different beast, and works differently to what you're doing here. An iframe is basically an embedded document, with it's own DocumentObjectModel (DOM) and, therefore, it's own base URL property.
In case you decide it's acceptable to modify the HTML string, you could do something like this:
var preview = xhr.responseText.replace('src="', 'src="testdirectory/');
Have in mind though that you would need to do the same for URLs in other types of attributes, such as href.

Using JavaScript (only - no libraries) to load another page into div

What is the JavaScript equivalent of $('content').load('page.html'); I am trying to load content in another page into my div but I cannot find a method for plain old JavaScript.
The good old JavaScript:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
var myRequest = new XMLHttpRequest(); //XMLHttpRequest is how you do it
myRequest.onreadystatechange = function(e){
if(myRequest.readyState == 4 && myRequest.status == 200){
var data = myRequest.responseText; //returned data
document.querySelector("div").innerHTML = data; //not safe but whatever
}
};
myRequest.open("get", "url here", true);
myRequest.send();
It is always better to do it with plain JavaScript first before using those fancy jQuery one-method-takes-care-of-everything-for-you methods.
Your question has two parts:
Grabbing some content on a server from the client
Pushing that content into a div.
For part one, see this thread for instructions on using XMLHTTPRequest():
HTTP GET request in JavaScript?
For part two, as for populating the div, it's this simple:
document.getElementById('content').innerHTML = 'someContent';
Note that you may want to scrub your content before populating the div depending on the source of the page you are requesting, as using JS to populate a div with raw HTML is an attack vector that hackers might try to exploit.
Have you tried taking a look at using iframes? http://www.w3schools.com/tags/tag_iframe.asp
It's called an XML HTTP Request (XHR). See the docs here.
As you can see from the source code here, jQuery's load() function calls the ajax() function to load the external html.
Under the hood, the ajax() function uses XMLHttpRequest which is how you would retrieve the file using vanilla JavaScript.

Categories

Resources