I'm trying to upload files in the background. I am not able to use any frameworks so I have to do manually. The page already contains a form, and the file input fields are located within that form, so I can't embed a form in a form so I need to move the file input around.
The problem with the code I'm using is that it doesn't seem to actually submit, I don't see any network activity at all. Can anyone spot anything wrong here?
<form>
...
<input id="photo-file-input" type="file"/>
<button type="button" onClick="uploadBackground('photo-file-input');">Upload</button>
....
</form>
function uploadBackground(fileInputId)
{
var iframe = createIframe('TEST');
var form = createUploadForm('TEST', 'upload.php');
var fileInput = document.getElementById(fileInputId);
var fileInputParent = fileInput.parent;
//move file input into generated form
form.appendChild(fileInput);
form.submit();
iframe.onload = function()
{
alert('file was uploaded');
//put the file input back where it was
fileInputParent.appendChild(fileInput);
//clean up generated elements
iframe.parent.removeChild(iframe);
form.parent.removeChild(form);
}
}
function createUploadForm(target, action)
{
var form = document.createElement('form');
form.display = 'none';
form.target = target;
form.action = action;
form.method = 'POST';
form.enctype = 'multipart/form-data';
return form;
}
function createIframe(name)
{
var iframe;
try
{
iframe = document.createElement('<iframe name="' + name + '">');
}
catch (ex)
{
iframe = document.createElement('iframe');
iframe.name = name;
}
return iframe;
}
You can not copy a file input element and set/keep its value. It is for security reasons. There is no reason why you need to create a new form. Just append an iframe to the page, set the target of form to the iframe name and submit the original form.
I have looking for the same problem and I think, I have found an solution, which will work for Firefox and Chrome and may be on IE 10 and above ( here I need some morr testing )
The solution is a little bit ugly because I use a frameset. But this is the only solution I have found so far.
The use case is:
We have a website with an product catalog, the editor can upload videos for each product.
The upload of the video need a long time, so I have look for an solution, where after you have chosen a video an start the upload, you can navigate to an other product and upload an other file without to wait until the download of the first is complete.
The test is based on some other work:
https://stackoverflow.com/a/1186309/2248340
https://stackoverflow.com/a/105074/2248340
How it works:
If you press submit, all you form data will be placed in an object. in this object is also the selected file list.
This object will push in an array requests in the upload frame.
here runs the watchdog and look if there are new requests ( status = 0 )
If it found one a new upload is started.
Here is my test project to try it:
The frameset:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<frameset rows="*,100">
<frame id="start" name="start" src="start.html">
<frame id="upload" name="upload" src="frame.html">
</frameset>
<noframes>
<body>
please use this
</body>
</noframes>
</html>
start.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Start</title>
<script src="../js/jquery-1.11.3.min.js" ></script>
<script>
var files;
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var UploadRequest=function(f)
{
var o= {};
o['guid']=guid();
o['action']=$('form').attr('action');
o['files']=files;
o['values']=$('form').serializeObject();
o['status']=0;
return o;
}
function fileSelect( e){
files=e.target.files;
return false;
}
</script>
</head>
<body>
<form id="test" action="phpinfo.php">
<input name="test" >
<input type="hidden" name="h1" value="2">
<input type="file" name="uploadfile" onchange="fileSelect(event)">
<input type="submit" value="upload‚" >
</form>
<script>
var olddogcounter=localStorage['uploadwatchdog'];
var check=false;
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
$(function() {
$('#test').submit(function() {
var request=new UploadRequest();
parent.upload.requests.push(request);
return false;
});
});
</script>
<a href="test.html" >test</a>
</body>
</html>
and the upload frame:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>frame</title>
</head>
<body>
<h1>frame</h1>
<iframe id="response" width="100%" height="200"></iframe>
<script>
var requests=new Array();
var counter=0;
function watchdog()
{
for(var i=0; i<requests.length; i++)
{
var request=requests[i];
if(request.status==0)
{
alert("watchdog :"+dump(request));
request.status=1;
uploadFile(request);
}
}
}
function uploadFile(request)
{
var url = request.action;
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
iframe=document.getElementById("response");
iframe.src="data:text/html;charset=utf-8," + escape(xhr.responseText);
}
};
if(request.files.length>1)
{
for(var i=0; i<request.files.length;i++)
{
var file=request.files[i];
fd.append("upload_file[]", file);
}
}
else
{
var file=request.files[0];
fd.append("upload_file",file );
}
for( var key in request.values)
{
fd.append(key,request.values[key] );
}
xhr.send(fd);
}
window.setInterval(watchdog,2000);
</script>
</body>
</html>
The solution is not complete, but I think is an good starting point.
ToDo:
- Show name of uploads in a list
- after upload remove request from array requests
- show progess bar for upload
- some error handling
Related
I have iframe in parent.html. Child.html sending the postMessage('documnent.cookie','*') to the parent window.
The problem is postMessage() send 'null'. postMessage() is triggered before iframe loading is completely done. I have to postMessage() to Parent window only if iframe completely loads the data.
Here is my code: parent.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<body id="Body" style="background-color:Silver">
<iframe id ="CA_FRAME_0" src="http://localhost/ibmcognos/bi/child.html" style="display:none"></iframe>
<script type="text/javascript">
window.addEventListener("message", function (e){
if(e.data == null){
alert('fail');
}else{
alert('sucess');
document.cookie="key=" +e.data + ";expires=0;path=/";
}
}, false);
</script>
<div id="arcContainer" class="arcContainer"></div>
<script type="text/javascript">
ARCPLAN.language = "XXX";
ARCPLAN.application = "lv02";
ARCPLAN.startDocName = "application.apa";
ARCPLAN.arcCgiSite = "http://localhost/.....";
</script>
</body>
</html>
//child.html
<!DOCTYPE html> <html> <head>
<title>COOKIE</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> </head> <body>
<script type="text/javascript">
function getCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while(i < clen) { var j = i
+ alen; if(document.cookie.substring(i, j) == arg)
return getCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if(i == 0)
break; } return null; }
function getCookieVal(offset) { var endstr = document.cookie.indexOf(";", offset); if(endstr == -1) endstr = document.cookie.length; return document.cookie.substring(offset, endstr); }
**parent.postMessage(getCookie("key"), "*");** </script>
**<iframe id ="CA_FRAME" src="http://localhost/ibmcognos/bi/" style="display: none;" ></iframe>** - *this url make the redirect from here and set the cookie, it takes time*
</body> </html>
Kindly provide me some suggestions. Thanks.
In this case we have a webpage A need to load another webpage B through iframe.
page A is loaded. we can add a custom event to listen page B load event.
page A code:
const iframeWin = document.getElementById('h5-iframe').contentWindow;
window.addEventListener(
'message',
(e) => {
const { data } = e;
console.log('receive page load', data);
if (data.pageLoaded) {
iframeWin.postMessage(youdata, '*');
}
},
false,
);
page B code:
window.addEventListener(
'message',
(e) => {
console.log('receive youdata', data);
const { data } = e;
},
false,
);
// after register listen function send this message to page A.
window.parent.postMessage({ pageLoaded: true }, '*');
Add an onload event to your iFrame:
<iframe id ="CA_FRAME" src="http://localhost/ibmcognos/bi/" onload="onCaFrameLoad(this)" style="display: none;"></iframe>
Then you can run JS code only after the frame has completely loaded:
function onCaFrameLoad() {
// wrap your post in this function
};
This way, the code will only run once the frame has finished loading.
PoC:
parent.html
<html>
<body>
PARENT- I get data from child
<br /><br />
<iframe id ="CA_FRAME_0" src="child.html"></iframe>
</body>
</html>
child.html
<html>
<body>
CHILD - I send data to parent - but only after CA_FRAME has loaded
<br /><br />
<iframe id ="CA_FRAME" src="inner.html" onload="onCaFrameLoad(this)"></iframe>
<script>
function onCaFrameLoad() {
alert('iframe has loaded! now you can send data to the parent');
};
</script>
</body>
</html>
inner.html
<html>
<body>
INNER - I load all my content, then the onCaFrameLoad function in child.html runs
<script>
alert('My Name is INNER - I load all my content first');
</script>
</body>
</html>
I am trying to create a simple Chrome Plugin - however I have come to an issue.
I am trying to detect a click on a div using a simple getElementById - however as the api call happens after the DOM is loaded the JS cannot 'find' any div's and gives an error and doesn't do anything after I click on the element.
How do I detect the click, after the data from the API has loaded? I have included some of my code below:
Thanks
document.addEventListener('DOMContentLoaded', function () {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function () {
inputBox = document.getElementById("postcodeInput").value
console.log(inputBox)
let xml = new XMLHttpRequest();
xml.open('get', "https://api.getaddress.io/find/" + inputBox + "/?api-key=SECRET&expand=true", false);
xml.send(null);
var data = xml
var arr = xml.responseText
var data = JSON.parse(arr)
var postcode = data.postcode
var addresses = data.addresses
console.log(addresses)
document.getElementById("postcode").innerHTML = postcode;
var text = "";
var i;
for (i = 0; i < addresses.length; i++) {
text += "<div id='addressClick' name=" + i + ">" + addresses[i].line_1 + "</div>" + "<br>";
}
document.getElementById("data").innerHTML = text;
clickFunc()
}, false);
}, false);
function clickFunc() {
var rowBox = document.getElementById("addressClick");
rowBox.addEventListener('click', function () {
console.log('asd');
}, true);
}
HTML
<!doctype html>
<html>
<head>
<title>Address Search</title>
<script src="popup.js"></script>
</head>
<body>
<h3>Address Search</h3>
<input type="text" id='postcodeInput' name="postcodeInput" value="KW1 4YT">
<button id="checkPage">Search</button>
<div class='results'>
<h3>Results - <span id='postcode'></span></h3>
<p id='data'></p>
</div>
</body>
</html>
<style>
body {
width: 200px
}
#addressClick:hover {
color: blue;
cursor: pointer
}
</style>
You can attach an EventListener to all the body and, at every click, detect if the clicked element is the desired one:
document.body.addEventListener('click', event => window.alert(event.target.innerText));
This can sound like an aggressive solution, but it's way less invasive than a MutationObserver
I am trying to check if the input name is already in a Google Sheet. However, I am getting this error:
Uncaught TypeError: google.script.run.doSomething is not a function.
Here is my Index.html file.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="meetingTitle" value=""> // Getting value here
<button onclick="checkName()">Check if available</button> //Calling function is is causing the error.
<p id=nameVerification><i>Click the button above to check availability.</i></p>
<script>
function checkName() {
var toPass = document.getElementById("meetingTitle").value;
prompt("toPass " + toPass);
google.script.run.doSomething();
}
function checkNameCS(checkNameSSReturn) {
if (checkNameSSReturn == "") {
document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
document.getElementById("meetingTitle").value = "";
} else {
document.getElementById("meetingTitle").value = checkNameSSReturn;
document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
}
}
function doSomething () {
var nameGiven = document.getElementById("meetingTitle").value;
var nameExists = false;
var nameVerified = false;
var name = nameGiven.toLowerCase();
name = strip(name);
prompt("name " + name);
var spreadsheetId = ''; //Sheet id entered
var rangeName = 'Sheet1';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (!values) {} else {
for (var row = 0; row < values.length; row++) {
if (name == values[row][0]) {
nameExists = true;
}
}
}
if (nameExists) {
checkNameCS("");
prompt("name2 " + " ");
return;
}
nameVerified = true;
prompt("name2 " + name);
checkNameCS(name);
return;
}
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');
}
</script>
</body>
</html>
I tried debuging it with prompts but with no success. It seems like the function do something is properly called. But the code stops working aftergoogle.script.run.doSomething();.
I have looked at the documentation for successhandlers but they dont solve the issue either.
How about this modification?
Issue of your script:
doSomething() of google.script.run.doSomething() is required to be Google Apps Script.
In your script, doSomething() is put in HTML (index.html), and a method for using Google Apps Script is included. When google.script.run.doSomething() is run, doSomething() cannot be found at Google Apps Script (code.gs). By this, such error occurs. And if doSomething() is run at HTML side, also an error occurs at Sheets.Spreadsheets.Values.get(), because Sheets.Spreadsheets.Values.get() is the method of Advanced Google Services with Google Apps Script.
If you put it to Google Apps Script (code.gs), Javascript which is used at the script of doSomething() is required to be modified.
Modified script:
In this modification, your script was separated to Google Apps Script (code.gs) and HTML (index.html). var nameGiven = document.getElementById("meetingTitle").value; and checkNameCS(name); are used in index.html.
By the way, before you run this script, please enable Sheets API at Advanced Google Services.
Google Apps Script: code.gs
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function doSomething (nameGiven) {
var nameExists = false;
var nameVerified = false;
var name = nameGiven.toLowerCase();
name = strip(name);
var spreadsheetId = '###'; //Sheet id entered
var rangeName = 'Sheet1';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (values) {
for (var row = 0; row < values.length; row++) {
if (name == values[row][0]) {
nameExists = true;
}
}
}
if (nameExists) {
return "";
}
nameVerified = true;
return name;
}
HTML: index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="meetingTitle" value="">
<button onclick="checkName()">Check if available</button>
<p id=nameVerification><i>Click the button above to check availability.</i></p>
<script>
function checkName() {
var toPass = document.getElementById("meetingTitle").value;
prompt("toPass " + toPass);
var nameGiven = document.getElementById("meetingTitle").value; // Added
google.script.run.withSuccessHandler(checkNameCS).doSomething(nameGiven); // Modified
}
function checkNameCS(checkNameSSReturn) {
console.log(checkNameSSReturn)
if (checkNameSSReturn == "") {
document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
document.getElementById("meetingTitle").value = "";
} else {
document.getElementById("meetingTitle").value = checkNameSSReturn;
document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
}
}
</script>
</body>
</html>
Reference:
Class google.script.run
This problem is only happening in IE (at least 8 and 9). After an element is dynamically added to the DOM, the contents of an embedded iframe are lost when the page is reentered with a BACK/FORWARD key. Just two small HTML files will reproduce the issue.
The first file is iframe.htm:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function mytrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b); /// will work if commented
}
function submitListing() {
mytrace('submitListing()');
var doc = document.getElementById("output_iframe")
.contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//mytrace('submitListing(): out');
}
</script>
</head>
<body>
<div id="trace_output"><br /></div>
<input type="button" onclick="submitListing();" value="Run" /><br />
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
The second file is report.htm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
LINK
</body>
</html>
Steps to recreate the issue (BACK KEY)
Place above content in two files
Browse the iframe.htm file
Press the Run button to load report.htm in the iframe
Click on the LINK link to load a different page
Press the browser BACK button to returned to the "cached" (lmao) page
iframe contents are gone!!!! (only in IE-- safari, chrome, firefox retain the contents)
Also..(FORWARD KEY)
Browse to an arbitrary page (for history, http://www.google.com works)
Load iframe.htm into the same tab
Press the Run button to load report.htm in the iframe
Press the browser BACK button to return to the first page
Press the browser FORWARD button to return to iframe.htm
iframe contents are gone again!!
Now comment out the line:
d.appendChild(b)
That one change allows everything to work in IE. However, my solution needs to make those kinds of DOM manipulations (heavy jQuery/AJAX app) AND be able to restore the iframe across browser BACK/FORWARD actions.
It seems that I will have to remember the contents of the iframe so that I can restore it when the page is accessed with the BACK/FORWARD keys. I'm not thrilled with this because sometimes the iframe content will be quite large and it could chew up a bit of memory and time to make another copy of the embedded document for the restore. I would love to hear some other ideas about how I could approach this. Thanks in advance.
EDIT
The following replacement to iframe.htm will work around the problem with IE. I'm going to rewrite this using jQuery and add some more logic to restore the scroll positions. I had hoped for something more elegant, but this is doing the job.
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function myTrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b);
}
var make_backup ="false";
function submitListing() {
make_backup = "true";
myTrace('submitListing()');
var doc = document.getElementById("output_iframe").contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//myTrace('submitListing(): out');
}
function iframe_load() {
myTrace("iframe loaded, is_cached=" + document.getElementById("is_cached").value);
if (make_backup == "true") { // only when submitting
var htm, doc;
make_backup = "false"
doc = document.getElementById("output_iframe").contentWindow.document;
htm = doc.documentElement.innerHTML;
document.getElementById("iframe_backup").value = htmlEscape(htm);
}
}
function bodyLoaded() {
var is_cached = document.getElementById("is_cached");
if (is_cached.value == "false") { // initial page load
is_cached.value = "true";
}
else { // BACK or FORWARD, restore DOM where needed
var htm;
htm = htmlUnescape(document.getElementById("iframe_backup").value);
var doc;
doc = document.getElementById("output_iframe").contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
}
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body onload="bodyLoaded();">
<div id="trace_output" style="height: 300px; border-width:1; background-color: Silver"><br></div>
<input id="is_cached" type="hidden" value="false">
<input id="iframe_backup" type="hidden">
<input type="button" onclick="submitListing();" value="Run"><br>
<iframe id="output_iframe" src="" onload="iframe_load();"></iframe>
</body>
</html>
EDIT 2
Rewritten with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe workaround2</title>
<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
var make_backup = "false";
$(document).ready(function () {
myTrace('document ready()');
var is_cached = $("#is_cached");
if (is_cached.val() == "false") { // initial page load
is_cached.val("true");
}
else { // BACK or FORWARD, restore DOM where needed
if ($.browser.msie) { // IE loses iframe content; restore
var htm = htmlUnescape($("#iframe_backup").val());
var doc = $("#output_iframe")[0].contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
myTrace('iframe contents restored');
}
}
$('#output_iframe').load(function () {
myTrace("iframe_loaded");
if (make_backup == "true") { // only when submitting
make_backup = "false"
if ($.browser.msie) {
var doc = $("#output_iframe")[0].contentWindow.document;
var htm = doc.documentElement.innerHTML;
$("#iframe_backup").val(htmlEscape(htm));
myTrace('iframe contents backed up');
}
}
});
$('#submit_listing').click(function () {
make_backup = "true";
myTrace('submitListing()');
var doc = $("#output_iframe")[0].contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache='+d.getTime());
});
});
function myTrace(msg) {
$('#trace_output').append(msg + '<br>');
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body>
<div id="trace_output"
style="height: 300px; border-width:1; background-color: Silver">
<br></div>
<div style="display: block;">
<input id="is_cached" type="text" value="false">
<input id="iframe_backup" type="text" type="hidden"></div>
<input id="submit_listing" type="button" value="Run"><br>
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
I have a page which does an AJAX call and loads an entire page. The page that gets loaded has some Javascript. The javascript works on page by itself when loaded, but when its gets loaded by AJAX, the Javascript does not work. I dont know what I am missing.
The code of the loaded page
<html>
<script type="text/javascript">
function showfield(name){
if(name=='lstbox')document.getElementById('div1').style.display="block";
else document.getElementById('div1').style.display="none";
}
function hidefield() {
document.getElementById('div1').style.display='none';
}
</script>
<head>
</head>
<body onload="hidefield()">
<form action = "test2.php" method = "post">
Please enter a name for the App <input type = "text" name = "name">
<table border = "1"><tr><th>Choose a Label</th><th>Choose an element</th></tr>
<tr><td><input type = "text" name = "label1" /></td> <td>
<select name = "elementtype1" id="elementtype1" onchange="showfield(this.options[this.selectedIndex].value)">
<option value = 'select'> Select </option>
<option value='txtbox'>Text Box</option>
<option value='lstbox'>List Box</option>
<option value='chkbox'>Check Box</option>
<option value='radio'>Radio Button</option>
</select></td><td><div id="div1">Enter Listbox options: <input type="text" name="whatever1" /></div></td></tr>
</table>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
The code of the loading(AJAX) page is
<html>
<head>
</head>
<body>
<script src="ajax.js" type="text/javascript"></script>
<script src="responseHTML.js" type="text/javascript"></script>
<div id="storage" style="display:none;">
</div>
<div id="displayed">
<FORM name="ajax" method="POST" action="">
<p>
<INPUT type="BUTTON" value="Get the Panel" ONCLICK="loadWholePage('appcreator.php')">
</p>
</FORM>
</div>
</body>
</html>
The ajax.js code
function createXHR()
{
var request = false;
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3) {
try {
request = new XMLHttpRequest();
}
catch (err1)
{
request = false;
}
}
}
return request;
}
The responseHTML.js code
function getBody(content)
{
test = content.toLowerCase(); // to eliminate case sensitivity
var x = test.indexOf("<body");
if(x == -1) return "";
x = test.indexOf(">", x);
if(x == -1) return "";
var y = test.lastIndexOf("</body>");
if(y == -1) y = test.lastIndexOf("</html>");
if(y == -1) y = content.length; // If no HTML then just grab everything till end
return content.slice(x + 1, y);
}
/**
Loads a HTML page
Put the content of the body tag into the current page.
Arguments:
url of the other HTML page to load
id of the tag that has to hold the content
*/
function loadHTML(url, fun, storage, param)
{
var xhr = createXHR();
xhr.onreadystatechange=function()
{
if(xhr.readyState == 4)
{
//if(xhr.status == 200)
{
storage.innerHTML = getBody(xhr.responseText);
fun(storage, param);
}
}
};
xhr.open("GET", url , true);
xhr.send(null);
}
/**
Callback
Assign directly a tag
*/
function processHTML(temp, target)
{
target.innerHTML = temp.innerHTML;
}
function loadWholePage(url)
{
var y = document.getElementById("storage");
var x = document.getElementById("displayed");
loadHTML(url, processHTML, x, y);
}
/**
Create responseHTML
for acces by DOM's methods
*/
function processByDOM(responseHTML, target)
{
target.innerHTML = "Extracted by id:<br />";
// does not work with Chrome/Safari
//var message = responseHTML.getElementsByTagName("div").namedItem("two").innerHTML;
var message = responseHTML.getElementsByTagName("div").item(1).innerHTML;
target.innerHTML += message;
target.innerHTML += "<br />Extracted by name:<br />";
message = responseHTML.getElementsByTagName("form").item(0);
target.innerHTML += message.dyn.value;
}
function accessByDOM(url)
{
//var responseHTML = document.createElement("body"); // Bad for opera
var responseHTML = document.getElementById("storage");
var y = document.getElementById("displayed");
loadHTML(url, processByDOM, responseHTML, y);
}
Javascript loaded in HTML through AJAX will not be executed.
If you want to include scripts dynamically, append <script> tags to the existing loaded page's <head> element.
execute the script with jquery rather than with innerHTML
//this is not working!
document.getElementById("chart-content").innerHTML = this.responseText;
//try this
$("#chart-content").html(this.responseText);
The script is outside the body tag, and the loader picks out only the code inside the body tag, so the script is not even part of what you add to the page.
Loading you Js within the <head> should work. use this.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', loadJs);
} else {
loadJs();
}
function loadJs() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/assets/script/editor-controlls.js';
script.defer = true
document.getElementsByTagName('head')[0].appendChild(script);
}