I`am working on a js file which was designed for a home page.
I would like to navigate from this page to other pages via a navigation menu bar.
The target pages are sharing the same templat(a html code), thus for going to a specific page I need to load a specific content, which is saved in a xml file, then pass its contents to the target page.
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
// Until this point I can load the specific content
// How can I get from the url of the target page
// a js document object, so that I can call getElementById(Id)
// to pass the specific content.
// For instance: Im currently opnening X1:= www.main.com
// und I would like to switch to X2 := www.targetpage.com
// target page which contains html the templat.
// The problem **document** represents currently X1
// but i would like to set it to X2 so that I can pass
// the content of xhr.responseText to it
var component = **document**.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
Thanks
Try this, I have added xhr.onload function, which populated text returned from response
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var component = document.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
You can also use onreadystatechange event instead of onload. click for more reference
Try this
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var com = document.getElementById(elementId);
com.innerHTML = xhr.responseText;
}
xhr.send();
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
Reference
Related
I am using xhlhttprequest to load an external html file. However I am trying to figure out how to load only a speicific DIV from that html file.
My external page is helpFile.html- it has dozens header <DIV>s, an each header DIV is a specific help section. On different pages, I want to be able load a specific section? How could I do this? As an example, on the dashboard.html page is a help ? icon, that when the user clicks on it, it will load just the helpFile.html#dashboard section out of the main helpFile.html page - the content would be loaded into a bootstrap modal.
Here is my code to retrieve the entire page, but how can I just retrieve the needed section.
<script>
var request;
function sendInfo() {
var url = "helpFile.html";
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
function getInfo() {
if (request.readyState == 4) {
var val = request.responseText;
document.getElementById('helpModal').innerHTML = val;
}
}
</script>
Use DOMParser and look for the element
if (request.readyState == 4 && request.status == 200) {
var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText;, "text/html");
var dashboardElement = doc.querySelector("#dashboard");
document.getElementById('helpModal').innerHTML = dashboardElement.innerHTML;
}
So I have a webpage with two image elements. It is basically a website where you upload an image and it encrypts a secret massage with steganography. I want to show the difference that is not otherwise visible and I found Resemble.js which is a library to compare images. It gets two files as arguments and I would like to use my image sources instead of files since I don't want to save the images generated.
To sum up, I want to get rid of the requests and get my images via sources in the HTML but I don't know how to get it to work with Resemble.js since it accepts only files.
How the second image is generated:
cover.src = steg.encode(textarea.value, img, {
"width": img.width,
"height": img.height
});
The JavaScript working with files:
(function () {
var xhr = new XMLHttpRequest();
var xhr2 = new XMLHttpRequest();
var done = $.Deferred();
var dtwo = $.Deferred();
try {
xhr.open('GET', 'static/original.png', true);
xhr.responseType = 'blob';
xhr.onload = function (e) { done.resolve(this.response); };
xhr.send();
xhr2.open('GET', 'static/encoded.png', true);
xhr2.responseType = 'blob';
xhr2.onload = function (e) { dtwo.resolve(this.response); };
xhr2.send();
} catch (err) {
alert(err);
}
$('#example-images').click(function () {
$.when(done, dtwo).done(function (file, file1) {
if (typeof FileReader === 'undefined') {
resembleControl = resemble('./static/original.png')
.compareTo('./static/encoded.png')
.onComplete(onComplete);
} else {
resembleControl = resemble(file)
.compareTo(file1)
.onComplete(onComplete);
}
});
return false;
});
}());
here is my html:
<html><body>
page starts here
this is a test page
top:
<script id="invoc_code" type="text/javascript">
window.onload = function() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
var body = document.body;
if (xhr.readyState == 4 && xhr.status == 200) {
if(body.firstChild){
body.insertBefore(xhr.response, body.firstChild);
} else {
body.appendChild(xhr.response);
}
}
};
xhr.open("GET", "http://google.com", true);
xhr.send();
};
</script>;
page ends here
</body></html>
line body.insertBefore(xhr.response, body.firstChild); results to "NotFoundError: An attempt was made to reference a Node in a context where it does not exist". Can you please tell me what is the reason?
Thanks in advance
The insertBefore method expects a DOM element as its first parameter. If the XHR response is a HTML string, then you need to create one using this. Depending on your required DOM output you could do something like this:
var newElem = document.createElement("div");
newElem.innerHTML = xhr.response;
body.insertBefore(newElem, body.firstChild);
Using this code below I can load an HTML page to a div, in my site, by clicking a link in my menu.
Now, the problem is that when it loads the HTML page into the div, it loads just fine... but without its original background color that should be loaded with the other content of the HTML page as well. All the other CSS elements seem to be just fine.
Thank you in advanced.
js code:
function processAjax(url)
{
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
}
catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
return false;
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
html:
<a onclick="return processAjax(this.href)" href="example.html">CLICK ME</a>
<div id="containerDiv"></div>
Get the style element from the page and append it to the head:
var styles = document.getElementsByTagName('style');
var head = document.getElementsByTagName('head')[0];
for(var x = 0; x < styles.length; x++){
head.appendChild(styles[x]);
}
Edit:
You want to set the returned html as an element first:
var div = document.createElement('div');
div.innerHTML = req.responseText;
var styles = div.getElementsByTagName('style');
for(var x = 0; x<styles.length;x++){
document.getElementsByTagName('head')[0].appendChild(styles[x]);
}
Use the new code, not the old, and put it in the if(reg.status == 200) block.
Change .innerHTML to .html, or just use .load(req.responseText)
.innerHTML overwrites everything I believe. You just want to change a section.
So I have simple html web page with one div with id="toFill" on it. Page has header script stule and body blocks. I have some file like markUpToAdd.html with for example html list (no header body etc - just <ul> <li> etc) jo my server will update file from time to time. I need using Javascript to put contents of markUpToAdd into that div and update each 30 seconds. How to do such thing? Not using Jquery or any special libs.
since you're not using a library, you'll have to do it he long way...
function update(){
var xmlhttp;
try{
xmlhttp = new XMLHttpRequest();
} catch(e){
var success = false;
var objects = ["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0; i<objects.length && !success; i++){
try{
xmlhttp = new ActiveXObject(objects[i]);
success = true;
}catch(e){};
}
if(!success) throw new Error("AJAX is unavailabe");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4){
document.getElementById('toFill').innerHTML = xmlhttp.responseText;
};
}
xmlhttp.open("get", "markUpToAdd.html", true);
xmlhttp.send(null);
}
update();
setInterval(update, 30000);
untested. could also be optimized (only need to determine the XHMLTTPRequest object once instead of during each tick).
If you use jquery you can use the function jQuery.get() [http://api.jquery.com/jQuery.get/]
$.get("markUpToAdd.html", function(data){
$('#toFill').innerHtml = data;
});