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

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.

Related

How to include an html file in javascript [duplicate]

I have some html pages with the same footer. With JavaScript and only JavaScript could I import another html page inside it?
Here's how you could use just javascript to add a footer to your page.
2022 code, using fetch and insertAdjacentHTML:
async function addFooter() {
const resp = await fetch("footer.htm");
const html = await resp.text();
document.body.insertAdjacentHTML("beforeend", html);
}
Original 2011 code, using XMLHttpRequest and innerHTML:
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function () {
document.body.innerHTML += ajax.responseText;
}
ajax.open("GET", "footer.htm");
ajax.send();
The 2011 code will still work in all browsers today, but fetch is more intuitive, and allows you to avoid coding an event handler callback. insertAdjacentHTML is also available for all browsers, so you could use that or innerHTML with either example. Only fetch is new, and won't work in IE without a polyfill.
As above, one method is to use jQuery load. I happened to be doing the exact same thing now, so will post a quick example.
Using jQuery:
$("#yourDiv").load('readHtmlFromHere.html #readMe');
And your readHtmlFromHere.html page would consist of:
<div><div id="readMe"><p>I'm some text</p></div></div>
You can use ajax to return a whole HTML page. If you wanted to replace the whole page you could replace the body tag and all it's children currently on the page with the body tag returned from the ajax call.
If you wanted to just replace a section you'd have to write a server-side script to create that section, then use ajax as above but just replace an element rather than the whole page.
Along with what #Alex mentioned, jQuery has a method .load() that you can use to fetch a specific portion of a page (See Loading Page Fragments heading on that page). You specify the URL you want to retrieve along with a selector (so if you wanted only a specific <DIV>'s contents for instance).
Following this answer example (one of the answer in this question), I made this little reusable function:
/**
* Render the array of html files, to the
* selected container.
* #param {*} pages - array of html file names
* #param {*} container - HTML element name
*/
function render(pages, container) {
const template = document.createElement("template");
var ajax = new XMLHttpRequest();
pages.forEach(element => {
// this is the route where the files are stored
ajax.open("GET", `./view/shared/${element}.html`, false);
ajax.send();
template.innerHTML += ajax.responseText;
});
document.querySelector(container).append(template.content);
}
export { render };
Which you can use in your index.js file, like so:
import { render } from "./tools/render.js";
var headerContent = ["siteName", "navbar"];
render(headerContent, "header");
This is rendering the html files siteName.html and navbar.html, into the <header> tag in the root index.html file of the site.
NOTE. This function works on localhost, but for whatever reason (which I still have to fix; I'll let you know when I do) it does not work correctly when working on GitHub Pages.
You could do a server side include, depending on your webserver.
but the quickest way would probably be to create a JavaScript file that uses document.write or similar to output the html syntax.
and then just include the created JavaScipt file the normal way.
more info at:
http://webdesign.about.com/od/ssi/a/aa052002a.htm
You definitely could, but if all you're doing is templating I recommend you do this on the server.
fetch("MyHTMLFile.html").then((response) => {
response.text().then((text) => {
targetHTMLElement.innerHTML = text;
});
})

Javascript read and display content of a file

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.

Load Local HTML Into Div (Chrome Extension)

I'm not using a framework and I want to implement an architecture whereby a single html file holds the skeleton of my layout, and certain other html snippets are loaded into various divs in that layout. The code is all in the same directory location inside my main extension folder /popup/
I want to build a very simple function to load the locally saved html snippets into the div elements. Here is my first attempt:
function loadView(viewName,destination){
var URL = "/popup/"+viewName;
var client = new XMLHttpRequest();
client.open('GET', URL, false);
client.onreadystatechange = function() {
document.getElementById(destination).innerHTML = client.responseText;
}
client.send();
}
// Example of a call
loadView('contact.html','widgetBox');
Obviously this is terrible because it relies on setting the ajax to asynch false. But under this solution, that is necessary because the next line of code in the script may/does try to manipulate the newly loaded content.
What would be a method for reaching a similar result, that does not depend on ajax? (or at least, which would resolve the need to use asynch false)
Notes:
I know that there are frameworks for basically this exact problem. I like to learn how to do things without frameworks. I am not challenging the use of frameworks, I'm just not interested in those approaches in this question. Relatedly, I'd like to avoid using jquery (and as this is a chrome extension, developing in clean JS isn't particularly painful).
The content of contact.html is some html, is just a string of html, (i.e. it does not have a header or any content besides that which I seek to load). I am open to another convention besides discrete .html files, but I like this convention as it is easy to keep my various page chunks organized, and keeping them as .html files allows me to read them easily in things that format html nicely.
You should have your loadView function accept a callback as a third parameter. Then, call it when the Ajax call completes. That way, you can use an async request.
function loadView(viewName, destination, callback){
var URL = "/popup/"+viewName;
var client = new XMLHttpRequest();
client.open('GET', URL);
client.onreadystatechange = function() {
if (client.readyState < 4) return; // Wait until the request completes
document.getElementById(destination).innerHTML = client.responseText;
callback();
}
client.send();
}
// Example of a call
loadView('contact.html', 'widgetBox', function() {
// Do whatever comes next
});

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.

Categories

Resources