Handling multiple call to a script - javascript

I'm working in an embed script while loads HTML form with JS validation while loaded in web pages. For now only one script loads on a page. If we add more embed script on a single page, the last added or loaded one will work & its related form & validation will execute. What I'm trying is to run multiple embed scripts in a single page.
Here is the current embed script pattern which is placed in HTML page:
<script src="http://link-to-my-embed-code-executer/embed_form.js"></script>
<div id="12345wertyui67890" class="form_wrap"><!-- HTML form with validation loads here --></div>
<script>
window.onload = function() {
EmbedManager.embed({
key:"12345wertyui67890",
is_embed_form:"1",
external_style:"1"
})
}
</script>
Here is the current script in embed_form.js
var EmbedManager = {
key: '',
is_embed_form: !0,
external_style: 0,
resizeCallback: function() {},
init: function(embedParams) {
EmbedManager.key = embedParams.key;
EmbedManager.is_embed_form = embedParams.is_embed_form;
EmbedManager.external_style = embedParams.external_style;
EmbedManager.serverUrl = ''; // Here is the URL which provide HTML Form as response
},
embed: function(embedParams) {
var xhr = new XMLHttpRequest();
xhr.open('POST', EmbedManager.serverUrl);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.onload = function() {
if (xhr.status !== 200) {
document.getElementById(EmbedManager.key).innerHTML = "Unable to load form"
}
var response = JSON.parse(xhr.responseText);
// Attempt to get the element using document.getElementById
var elementDOC = document.getElementById(EmbedManager.key);
// If it isn't "undefined" and it isn't "null", then it exists.
if ((typeof(elementDOC) != 'undefined') && (elementDOC != null) && (EmbedManager.is_embed_form)) {
// Only for Form, not used in LP
document.getElementById(EmbedManager.key).innerHTML = response.form_html;
}
}
// More code here to load Form in place of embed script & do validations
}
}
I'm trying to manage the updates in JS file because embed scripts are already provided to clients & I'm not interested in making bigger updates in those embed scripts. If it could be handled inside the JS file, it will be better.
What I'm trying to do is add a new function remapEmbed which will be a copy of codes in current embed function & also after that will replace codes in embed function to such a manner to collect multiple requests from embed scripts & make an array, later I will call remapEmbed function to do the rest. I know little changes will be needed there also, I will look into it later.
Here is the expected script in embed_form.js
var EmbedManager = {
key: '',
is_embed_form: !0,
external_style: 0,
resizeCallback: function() {},
init: function(embedParams) {
EmbedManager.key = embedParams.key;
EmbedManager.is_embed_form = embedParams.is_embed_form;
EmbedManager.external_style = embedParams.external_style;
},
remapEmbed: function(embedParams) {
// Code which was in `embed` function
// More code here to load Form in place of embed script & do validations
},
embed: function(embedParams) {
// Code to collect request & make a array
// Expecting to add codes here
// Later will call `remapEmbed` function & do rest.
EmbedManager.remapEmbed(embedParamsOne);
}
}
But the issue is that I'm getting only the call from the last embed script which is added on the page. It might be because of the last call overwriting the previous ones. How can I handle multiple requests?
Here I'm adding the Codepen, so you can check the code.

Unfortunately, you cannot place multiple onload events on a single
page. You can nest multiple functions within the one onload call. Ref
It working fine with Your script. Because you are calling embed scripts in Onload. Make sure all scripts inside last window.onload function.
Change html to
<!-- The embed code that will not replace with the response -->
<div id="12345AAA67890" class="form_wrap">HTML form with validation loads here: First Embed Code</div>
<!-- This embed code will be replaced with HTML content -->
<div id="12345BBB67890" class="form_wrap">HTML form with validation loads here: Second Embed Code</div>
<script>
window.onload = function() {
EmbedManager.embed({
key:"12345BBB67890",
is_embed_form:"1",
external_style:"1"
})
EmbedManager.embed({
key:"12345AAA67890",
is_embed_form:"1",
external_style:"1"
})
}
</script>
Hope this is the solution you are looking.

Related

append script and links work in practice but not in application

I am using js to get the HTML for my websites navbar. instead of having to paste it on each page,
that part works great. the issue is afterwards i create a script and link element, to provide the javascript and the css file that goes with the navbar. using brackets application it works. but in real world application i'm getting error 404, i've checked the location and it seams to be correct.
also. is there a way to tell when the html from the fetch method is completed? i have a set timeout() function of 6ms as without it it's a 50-50 shot of loading the js file before the html. like a window.onload() command.
//Getting include attribute value
function getHTML() {
var includes = document.getElementsByTagName('include');
for(let i=0; i<includes.length; i++){
let include = includes[i];
//Loading include src value
load_file(includes[i].attributes.src.value, function(text){
include.insertAdjacentHTML('afterend', text);
include.remove();
});
}
const body = document.getElementsByTagName('body')[0],
script = document.createElement("script"),
head = document.getElementsByTagName('head')[0],
link = document.createElement('Link');
link.setAttribute('rel',"styleSheet")
link.setAttribute('href','/wont-work');
head.appendChild(link)
setTimeout(()=> {
script.setAttribute("src","/Navbar.js");
script.setAttribute("type","text/javaScript")
body.appendChild(script);
},6);
}
function load_file(filename, callback) {
fetch(filename).then(response => response.text()).then(text => callback(text));
console.log('file loaded')
}
window.addEventListener("load", getHTML);
expecting the CSS and Javascript to NOT be 404

How to change URL without load in JavaScript

I have a question How to change URL without load. I am working on a PHP, JavaScript project.
I am try to make without load Home page. in home Header section content some buttons like :-
Header
on click button than load data using XMLHttpRequest() and i want to change Url like:-
https://example.com/home to https://example.com/search
Code
var xmld = new XMLHttpRequest();
xmld.open("GET", "/Api/SearchPage", true);
xmld.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmld.onreadystatechange = function() {
if (xmld.readyState == 4 && xmld.status == 200) {
var json = JSON.parse(xmld.responseText);
if (json.Status == "Ok") {
doument.querySelector("#content").innerHTML = json.HTMLData;
window.location.href = "https://exmaple.com/Search"; // without load
}
}
}
xmld.send();
in example, when you click item than url change without load
I am not use any js and php framework
Example
https://dribbble.com/
https://in.pinterest.com/
it's possible??
if you don't use a framework window.history.pushState() will do the thing you want.
See this link: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
Use a state manager like Redux with a modern Javascript framework like ReactJs.

Content Controls getting lost when loading docx file via OOXML into another Word document

I have a Word Add In that loads a Word document into the current document. This is working just fine with the below code.
var myOOXMLRequest = new XMLHttpRequest();
var myXML;
myOOXMLRequest.open('GET', 'template.xml', false);
myOOXMLRequest.send();
if (myOOXMLRequest.status === 200) {
myXML = myOOXMLRequest.responseText;
}
Word.run(function (context) {
Office.context.document.setSelectedDataAsync(myXML, { coercionType: 'ooxml' });
});
Now I added some content controls to the Word document which I saved as template.xml (that serves as my template). When I now save the Word document containing the content controls as XML, and try to load it via the above code snippet, all works fine but the content contros are gone! I can't access them from Word, nor can I access them via Javascript like so:
var name = context.document.contentControls.getByTitle('myContentControl');
context.load(name);
return context.sync().then(function () {
var nameNew = name.items[0];
nameNew.insertText("Test", "Replace");
return context.sync().then(function () {
});
});
Is this a bug or is this just not possible? I also thought about putting some placeholders like ##myValue## into the Word template and then replacing those with values, but I'd rather do it with ContentControls if that is possible.
EDIT:
Here is the XML that I have created from my template: http://pastebin.com/NX0ZqLiM
I created the XML by just saving the Word document as XML and then loading as described above. Funny thing is, when I run the sample now I can see the content controls in Word. But when I try to access them via Javascript the ContentControl collection is always empty. I used a code sample from here https://dev.office.com/reference/add-ins/word/contentcontrol?product=word to try to access the content controls, but the collection of items is always empty.
Let me know if you need any more information.

How to receive data from html form POST at other html page?

I have a html page called index.html. Inside it I use js to send JSON to other page (loja.html) and right after that I load this page. I would like to read the contents of JSON on loja.html and use it to populate some html tags. Here's my code:
piece of index.html's
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
}
}
ajax.open("GET", "http://localhost:8080/DBRest/loja.html",true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(dataToJSON(nome,idade));
console.log(dataToJSON(nome,idade));
window.location = 'http://localhost:8080/DBRest/loja.html';
piece of loja.html's js:
window.onload = function() {
alert('alert');
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
alert(JSON.parse(ajax.responseText));
}
}
}
When I load loja.html from index.html none of alerts are displayed. when typed on browser, only first alert is displayed. How can I correctly send data to loja.html from index.html and after it immediately load loja.html?
Javascript lives/executes within the current browser window/location; if loja.html isn't currently loaded, it won't do anything as the javascript on that page hasn't been run. You'll need a server-side component to accept the GET (not POST) request that you're making and store the data. loja.html can then load that via Javascript.
You have a few options to move data between pages:
Store Data in Local Storage
Store Data in a cookie
Add data to the URL via query parameters
Query the database on the new page to retrieve the data.
Without using a SPA, there isn't a direct way to move data from one html page to another html page.

How can I set the http RequestHeader for a file load in the $script.js library?

The $script.js library I am using
https://github.com/ded/script.js/
has the following Javascript. What I need to do is set the request header in this code block but I am not sure how to do this:
var el = doc.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
return false;
}
el.onload = el.onreadystatechange = null;
loaded = true;
// done!
};
el.async = true;
el.src = path;
document.getElementsByTagName('head')[0].insertBefore(el, head.firstChild);
Here's an example of something similar (not part of $script.js) that does set the request header:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
The first code block (the one I need to use but can modify slightly) is not very clear to me. Does anyone know how I can change this first code blocks (used in $script.js) to set the request header?
If I'm interpreting the library correctly, XMLHttpRequest isn't used directly by $script.js. It appears to be creating <script></script> tags dynamically and letting the browser handle downloading the script files. Using this library, it does not appear you can specify custom headers.
Altering the request headers the browser sends via Javascript is not possible according to some of the articles I've read including the answer to this question on SO: Is it possible to alter http request's header using javascript?
If you want to set custom headers, you'll need to use a dynamic loading library which uses XHR to load the scripts. Here is another article I've found with patterns for this type of functionality: On-Demand Javascript.

Categories

Resources