Javascript SELECT attribute's OPTION is not working inside any method - javascript

I am facing a strange problem. Please see my code clearly.
While I am calling my following function in the root of my js file it is smoothly working.
function setOptionValueWithNameAndOid(select, name, oid){
//here first parameter 'select' is my SELECT which is written in HTML and just pass the ID of that SELECT and 'name' and 'oid' is simple string
var option = document.createElement("option");
option.setAttribute("value", oid);
var textNode = document.createTextNode(name);
option.appendChild(textNode);
select.appendChild(option);
}
if I call this function in the body of my js file like
setOptionValueWithNameAndOid(select, name, oid)
So this is perfectly working. Select option is adding.
But problem occurs when I call this function inside any event or inside any function.
Please see this code carefully:
function loadNameOidSelect(url, select){
//here 'url' is my API url. and select is the same SELECT. just passing the id
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(dta => {
setOptionValueWithNameAndOid(select, dta.NAME, dta.OID); // from API i am getting 'name' and 'oid'
});
} else {
console.log('error');
}
}
request.send();
}
but now problem is if I call the same method inside this api calling no option is adding in my SELECT.
But If I call the same method in the page load with some static data it is perfectly working.
So can you please help me what actually problem?

Related

HTML added from another HTML file using JS displays correctly, but JS functions do not work

I would like an element of my html page to be taken from another html file. So, such a widget displayed on many pages at once.
I was able to write JS code so that the content of the element is taken from another file. Code below:
//* Accordion - replace */
var fn = (event) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", '/widgets/accordion.html', true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText)
document.getElementById("accordion").innerHTML = xhr.responseText;
}
else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null); }
document.addEventListener('DOMContentLoaded', fn, false);
document.addEventListener
The item (accordion) displays correctly, as in the code here:
https://codepen.io/jakub-czeszejko-sochacki/pen/rNWNwrN
But unfortunately it doesn't work properly as if JS code is not being read for this element. As a result, when you click on the accordion button, the accordion does not open.
Is it even possible for this to work with JS?
Problem solved.
It turned out that the JS accordion initiation took place before its html was loaded with the line:
document.getElementById ("accordion"). innerHTML = xhr.responseText;
It was enough to put the initialization code (the accordion opening code) in the function and call this function after the above line of code.

Javascript - Is it possible to change location, and start manipulating the new document

I'm trying to switch between pages and then to manipulate the new document through javascript or jQuery.
However, when I run my example, it manipulates the first document and then changes location. Is it even possible?
this is my example(i even tried to call a function after changing location):
function openSide(x) {
//é passado o botão carregado
window.location.href = 'new.php';
var id = x.innerHTML;
open(id);
}
function open(x) {
$("#div1").css("display","none");
$("#div2").css("display","");
$("#tituloPlay").html(id);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$("#tabelaOuvirPlaylist").append(xhttp.responseText);
//console.log(xhttp.responseText);
}
};
xhttp.open("POST", "php/listarMusicasDePlaylist.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id="+ x);
}
Use the jQuery load() method to take data from that location and put it on your page. Then you can manipulate it from there.
Since you're opening a new PHP page, why don't you just pass the ID as a query parameter?
new.php?id=1
Adjust your PHP file to read the ID from $_GET ["id"]..
To use the ID in Javascript you would need to read the current location and do a substring the = sign or you could have PHP create a hidden DOM element and read it's value in Javascript

can xmlhttpRequest response wait even after onload

I am loading a page through xmlHttpRequest and I am not getting one variable which come into existance after some miliseconds when page loading is done
so the problem is when xmlHttpRequest sends back the response I do not get that variable in it.
I want it to respond back even after onload.
var xhr = new XMLHttpRequest();
xhr.open("GET", event.url, true);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() { callback(); };
xhr.followRedirects = true;
xhr.send();
I tried setTimeOut but of no use because may be at that time call is finished
xhr.onload = function() {
console.log('wait for response');
setTimeout(function(){
callback(xhr.responseText);
},2000);
};
I tried readyStateChange , but no success
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
callback(xhr.responseText);
};
};
by the way, I am trying to load amazon signIn page
and the variable which is missing everytime is hidden Input Field metadata1,
I get all other hidden Input fields in response text , except input field, named "metadat1"
I'll be more than Happy, If anyone can help.
Thanks in advance
ohh Finally I did it,
I din't read any javascript, Instead I just extracted scripts which I received in xhr calls and executed it inside a hidden div, and here it is , I got that variable's value
abc(xhr.responseText);
function abc(xhrRes){
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrdiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var scr = document.getElementById('xhrdiv').getElementsByTagName("script");
//5 scripts needed to generate the variable
for(i=0;i<5;i++){
eval(scr[i].innerHTML);
if( i+1 == 5){
var response = document.getElementById('xhrdiv').innerHTML;
return response; //and in this response variable I have every thing I needed from that page which I called through xmlhttp Req
}
}
}
---------------------Improved Version-----------------------
Instead of executing script through eval,
keep script content in a file AND Include it, as we normally include the script, that works better.
xhrRes = xhr.responseText;
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrDiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var xhrDiv = document.getElementById('xhrDiv');
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = JSfile;
xhrDiv.appendChild(newScript);
(it shows the edit is done my anonymous user, :( because I forgot to Login, while editing)
If the data doesn't exist until some time after the page has loaded then, presumably, it is being generated by JavaScript.
If you request the URL with XMLHttpRequest then you will get the source code of that page in the response. You will not get the generated DOM after it has been manipulated by JavaScript.
You need to read the JavaScript on the page you are requesting, work out how it is generating the data you want to read, and then replicate what it does with your own code.

Add javascript function dynamically inside script tag

Below function needs to be added dynamically inside a script tag which is also generated dynamically.
var targetFunction=function(){
var sOut='<?xml version="1.0"?>\n';
sOut+='<Logon username="" password="" appversion="1.0">\n';
sOut+='\n</Logon>'
document.getElementById("KXML").value=sOut;
console.log(document.getElementById("KXML").value);
var httpReq = createXMLHttpRequest();
httpReq.open("POST", 'http://my-url', true);
httpReq.setRequestHeader("Content-type","application/xml");
httpReq.setRequestHeader('Accept', 'application/xml');
httpReq.setRequestHeader('X-REST-API', true);
httpReq.onreadystatechange = function() {
if (httpReq.readyState == 4 && httpReq.status == 200) {
document.getElementById('upload_target').innerHTML="";
var serverResponse = httpReq.responseText;
document.getElementById("upload_target").contentWindow.document.body.innerHTML=httpReq.responseText;;
}
}
httpReq.send(document.getElementById("XML").value);
}
This function will be added in an iframe dynamically. To do this I need it to convert it into string.
I tried converting it to string by
alert(eval(targetFunction.toString()));
I was not able to do so.Any help is appreciated.
Have you tried using the String() function?
See more here: http://www.w3schools.com/jsref/jsref_string.asp
Edit:
Have you tried removing the eval?
alert(targetFunction.toString());

Load Javascript into ajax loaded content

I am new to working with AJAX and have some experience with Java/Jquery. I have been looking around for an solution to my problem but i cant seem to find any.
I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page.
I got it working by using this code:
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
$("#product-overlay-inner").load(myUrl, function() {
});
$("#product-overlay").fadeIn();
return false;
});
product-slot a = Link to the product in the category page.
product-content = the div i want to insert in the popup from the product page.
product-overlay-inner = The popup window.
product-overlay = The popup wrapper.
The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup?
I hope you can understand what my problem is!
Thank you in advance!
EDIT: The platform im using has jquery-ui-1.7.2
I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option.
I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class.
I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary.
The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page.
here's a basic implementation based on the register route handler:
var register = function(){
$(".page").html("");
// use the getText ajax function to get the page content:
getText('partials/register.php', function(content) {
$(".page").html(content);
var script = document.createElement('script');
script.src = "js/register.js";
$(".page").append(script);
});
};
/******************************************
* Ajax helpers
******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
// if the request is complete and was successful -
if (request.readyState === 4 && request.status === 200) {
// check the content type:
var type = request.getResponseHeader("Content-Type");
if (type.match(/^text/)) {
callback(request.responseText);
}
}
};
// send it:
request.send(null); // nothing to send on GET requests.
}
I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily.
I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario.
I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :)
Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML.
Solution: pull down raw page with a get and reattach any Javascript blocks.
Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript):
_loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
{
// Regular expression to match <script>...</script> block
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts: string = "";
var match;
// Do an async AJAX get
$.ajax({
url: url,
type: "get",
success: function (data: string, status: string, xhr)
{
while (match = re.exec(data))
{
if (match[1] != "")
{
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
// Replace the contents of the panel
//panel.html(data);
// If you only want part of the loaded view (assuming it is not a partial view)
// using something like
panel.html($(data).find('#product-content'));
// Add the scripts - will evaluate immediately - beware of any onload code
panel.append(scripts);
if (callback) { callback(); }
},
error: function (xhr, status, error)
{
alert(error);
}
});
}
Plain JQuery/Javascript version with hooks:
It will go something like:
var _loadFormIntoPanel = function (panel, url, callback) {
var that = this;
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts = "";
var match;
$.ajax({
url: url,
type: "get",
success: function (data, status, xhr) {
while(match = re.exec(data)) {
if(match[1] != "") {
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
panel.html(data);
panel.append(scripts);
if(callback) {
callback();
}
},
error: function (xhr, status, error) {
alert(error);
}
});
};
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
_loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
// Now do extra stuff to loaded panel here
});
$("#product-overlay").fadeIn();
return false;
});

Categories