How do I append HTML from a document loaded with AJAX? - javascript

I am trying to append the contents of a .html file to the body of my main page. Basically, I am trying to make a reusable chunk of html that I can load into any page with a simple JavaScript function.
Here is the content of my nav bar, the content I want to reuse:
<div id = "navbar">
<div class = "Tab">
<h1>Home</h1>
</div>
<div class = "Tab">
<h1>Contact</h1>
</div
</div>
That is in a file called navbar.html
Now in my main index.html I want to import it by doing something like this:
<head>
<script src = "importHTML.js" type = "text/javascript"></script>
</head>
<body>
<script type = "text/javascript">
importHTML("navbar.html");
</script>
</body>
That should take care of importing the html in navbar.html.
The content of importHTML.js is this:
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
//This is the problem line of code
//How do I get the contents of my response to act like an element?
document.body.appendChild(this.responseText);
}, false);
xmlhttprequest.open("POST", url_, true);
xmlhttprequest.send(null);
}
So, I guess my question is pretty simple: How do I convert that response text to an HTML element so I can append all of it to the body?

Ajax HTML Injection
jQuery $.get() and JavaScript XMLHttpRequest()
This is a demonstration of 2 ways to inject, include, import, etc. There's 3 pages:
index.html
It has 2 links and 2 divs
data1.html
It's data will be imported to index.html by $.get()
data2.html
It's data will be imported to index.html by XMLHttpRequest()
I added jQuery to show the difference in complexity, but they do the same thing. The live demo is at the end of this mess.
jQuery $.get() Setup
HTML on index.html
div#data1 is the element that'll have the HTML of data1.html appended to it.
<h3 id="import1">
Import data1.html by jQuery<code>$.get()</code>
</h3>
<div id="data1"></div>
jQuery on index.html
$('#import1').on('click', function(e) {
e.preventDefault();
$.get('data1.html', function(data) {
$("#data1").html(data);
});
});
JavaScript XMLHttpRequest() Setup
HTML on index.html
div[data-x] is the element that'll have the HTML of data2.html appended to it.
<h3 id="import2">
<a href="">
Import data2.html by JavaScript<code>XMLHttpRequest()</code>
</a></h3>
<div data-x="data2.html"></div>
javaScript on index.html
function xhr() {
var tags, i, clone, file, xhttp;
tags = document.getElementsByTagName("*");
for (i = 0; i < tags.length; i++) {
if (tags[i].getAttribute("data-x")) {
clone = tags[i].cloneNode(false);
file = tags[i].getAttribute("data-x");
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
clone.removeAttribute("data-x");
clone.innerHTML = xhttp.responseText;
tags[i].parentNode.replaceChild(clone, tags[i]);
xhr();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
document.getElementById('import2').addEventListener('click', function(e) {
e.preventDefault();
xhr();
}, false);
README.md
Plunker
Note: This demo relies on user interaction via anchor links. This of course is probably not exactly what you need. You probably want it automatically loaded, so the following modifications are needed:
jQuery
$(function() {
$.get('data1.html', function(data) {
$("#data1").html(data);
});
});
JavaScript
(function xhr() {
xhr();
var tags, i, clone, file, xhttp;
tags = document.getElementsByTagName("*");
for (i = 0; i < tags.length; i++) {
if (tags[i].getAttribute("data-x")) {
clone = tags[i].cloneNode(false);
file = tags[i].getAttribute("data-x");
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
clone.removeAttribute("data-x");
clone.innerHTML = xhttp.responseText;
tags[i].parentNode.replaceChild(clone, tags[i]);
xhr();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
})();

Interestingly there is an upcoming W3C draft for HTML imports
https://www.w3.org/TR/html-imports/
Until then we can append the required markup to the DOM using Javascript.
JQuery approach
$(document).ready(function(){
$( "body" ).load( "navbar.html" );
});

Js haven't native method for this task, but you can use jquery method load
${element}.load('./template.html');
Or, create element-container, and use innerHTML prop
request.addEventListener("load", function(event_) {
//This is the problem line of code
//How do I get the contents of my response to act like an element?
var container = document.createElement("div");
container.innerHTML = this.responseText;
document.body.appendChild(container);
}, false);
UPD
Convert string to DOM.
function strToDom(str) {
var tempEl = document.createElement('div');
tempEl.innerHTML = str;
return tempEl.children[0];
}
NOTE: string element should be one root element, that wraps others
<div> ... </div>
not
<div></div><div></div>

The importHTML.js file will look like this :
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
var iDiv = document.createElement('div');
iDiv.innerHTML = this.responseText;
document.getElementsByTagName('body')[0].appendChild(iDiv);
}, false);
request.open("POST", url_, true);
request.send(null);
}

I assume you can create a div and then modify the div.innerHTML to have the content of the response:
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
var myDiv = document.createElement("div")
myDiv.innerHTML = this.responseText
document.body.appendChild(myDiv);
}, false);
xmlhttprequest.open("POST", url_, true);
xmlhttprequest.send(null);
}

you need a reference to DOM to know where to innest your loaded page. in your case you could think about appending it to body like this:
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
document.body.innerHTML += this.responseText
}, false);
xmlhttprequest.open("POST", url_, true);
xmlhttprequest.send(null);
}

Related

HTML- How can I insert the contents of a .txt file into a variable to use .innerHTML to change the contents of <body>?

Im trying to create an automated system for HTML page handling where I will be able to change the contents
of a<div> inside <body> by writing into an external .txt file and uploading it to the server. Im still an early student in university
and I havent learned PHP and JQuery yet. So I am trying to accomplish this by using only Javascript and HTML.
I just need a way for whatever I write inside the .txt file to be written again inside the <div class="CONTENT" id="target"> which is inside the <body> automatically. Any thoughts and suggestions are greatly appreciated!
You can solve your problem by using the FileReader.
Have a look to
this answer.
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('target');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<html>
<head></head>
<body>
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<div id="target" class="CONTENT"></div>
</body>
</html>
You can make an AJAX call for the text file and take the response from that call and set that as the .textContent of the div. Here's an example (see comments inline):
const output = document.getElementById("output");
// Create XHR object
var xhr = new XMLHttpRequest();
// Configure the request (substitute a URL
// to the file below)
xhr.open("GET", filePathHere, false);
// Set up the callback for when the response has
// been recieved
xhr.onreadystatechange = function (){
if(xhr.readyState === 4) {
// Was the request successful?
if(xhr.status === 200 || xhr.status == 0) {
// Populate the <div> with the response text
output.textContent = xhr.responseText;
}
}
}
xhr.send(null); // Make the call
<div id="output"></div>

jQuery inside dynamically generated element doesn't run

I have an index which shows a list of orders, each of which calls a function (named dynamically with PHP when I brought the data from the db), to simplify I've reduced the function that each div contains to just an alert. But also every minute an ajax function executes that searches for new orders and appends them on top, with the exact same code as the ones initially loaded. The jQuery works perfectly in the elements that are loaded initially but doesn't work at all in the elements generated dynamically.
This is the index with one initial order inside, BEFORE newOrders runs for the first time. The alert on that order functions properly
<div id="content">
<div id="pedido_4126" class="pedido">
<h4>Pedido 4126</h4>
<button id="btn4126">Alert</button>
<script>
alert("Pedido 4126");
</script>
</div>
</div>
<script>
function newOrders() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "simplereq.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#content');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval(newOrders, 60000);
</script>
And this is the index when the function has executed once and appended a new order on top with it's corresponding script, dynamically generated and received from the AJAX call:
<div id="content">
<div id="pedido_4255" class="pedido">
<h4>Pedido 4255</h4>
<button id="btn4255">Alert</button>
<script>
alert("Pedido 4255");
</script>
</div>
<div id="pedido_4126" class="pedido">
<h4>Pedido 4126</h4>
<button id="btn4126">Alert</button>
<script>
alert("Pedido 4126");
</script>
</div>
</div>
<script>
function newOrders() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "simplereq.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#content');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval(newOrders, 60000);
</script>
As you can see, the html and script are exactly the same, but the one on the new order brought by the ajax call, doesn't work.
Ok, so doing more research I came upon the best answer for my case, I'll leave it here in case it helps someone:
In the content I generate in the AJAX call, I print the scripts like this, and obviously hide it with css:
<div class="javascript">
$("body").on("click","#btn4255",function(){
alert("Pedido 4255");
});
</div>
And then I execute this function every time the AJAX call is returned
$('.javascript').each(function() {
eval($(this).text());
});
I only evaluate strings I generate myself so in this case I think it's not unsafe to use eval().

How do I make a post and return the contents into <div> tags?

I came across the question : How do I load an HTML page in a <div> using JavaScript?
I want to basically do the same thing with POST data but I'm not sure where to start.
The existing script works with get requests only?
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
I would like to avoid using jQuery if I can avoid it.
You can use the same ajax example you had posted in your comment, by changing the http://www.yoursite.com/home.html to home.html
Similar to below
In Javascript,
<script>
function load_home(e, getwhat){ // <--- send which html file to get and display the content in argument 'getwhat'
e.preventDefault();
var con = document.getElementById('content');
var xhr = new XMLHttpRequest();
xhr.open("POST", getwhat, true); // <-- this is post request
//xhr.open("GET", getwhat, true); // <-- this is get request
xhr.setRequestHeader('Content-type', 'text/html');
xhr.onreadystatechange = function(e) {
if(xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.send();
}
</script>
In HTML,
HOME
ABOUT US
SERVICE
<div id="content"></div>
The best aproach is to use jquery like this working demo
html
<nav id="menu" class="menu-side">
About
Help
Contact
</nav>
<div id="target">
<!-- content is being loaded here from other .html files -->
</div>
javascript
$(function() {
var $menu = $('#menu'),
$target = $('#target');
$menu.on('click', '> a', function(event) {
var $this = $(this);
event.preventDefault();
$target.load($this.attr('href'));
});
})

I Need create an html page that reads a XML file in a CD-R. How I can do that?

I made an html website that will be running in a CD-R (this will be a manual).
I have the page created and everything is working good, but at this moment I'm having some problems for opening a XML file.
My question is, is this possible, since It will be running in a CD Drive?
Thank you
This is what I have:
function testing()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "teste.txt", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
var allText = rawFile.responseText;
alert(allText);
}
else
alert("erro no xml");
}
rawFile.send();
}
This works fine in for example: localhost/path
But i want it to work in a path like c:\path\
If you don't mind modifying your source files a little bit by turning it into JSON, you could use JSONP. Here's a simple example:
<button onclick="go();">Click me</button>
<script type="text/javascript">
function go() {
var scriptTag = document.createElement("script");
scriptTag.src = "someText.js";
document.getElementsByTagName("body")[0].appendChild(scriptTag);
}
function jsonCallback(txt) {
console.log(txt);
}
</script>
File: someText.js:
jsonCallback("Hello World!");

How can I parse a text file using javascript

The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request

Categories