Javascript function returns variables as undefined - javascript

I am dynamically including a javascript file into a html page, which works fine. But when I run the function 'tryData' from the file the variables return as undefined. I've been looking for hours can't find a similar problem anywhere, does anyone know what the problem is?
function in external file:
function tryData(id, size){
document.getElementById('content').innerHTML = '<iframe src="http://domain.com/feeds/'+id+'/'+size+'/" id="frame"></iframe>';
if(window.data){
clearInterval(timer);
data();
}
}
the line I am using to call it:
tryData(131, 'large');
I know that the function is running because the frame is inserted as expected, but there's no content as the URL for the frame reads 'domain.com/feeds/undefined/undefined/', instead of 'domain.com/feeds/131/large/'.
Thanks in advance for any help :)
Here is an example of a html page with the function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="robots" content="NOINDEX,NOFOLLOW" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<!-- Widget -->
<div id="content"></div>
<script>
(function(d, s) {
var js = d.createElement(s), ins = d.getElementsByTagName(s)[0];
js.src = "http://domain.com/feeds/insert.js";
ins.parentNode.insertBefore(js, ins);
tryData(131, 'large');
}(document, 'script'));
</script>
<!-- Widget End -->
</body>
</html>
here is the js file:
function data(){
var u;
u = document.URL;
$.post("http://domain.com/data.php", { u: u} );
}
function tryData(id, size){
document.getElementById('lsb').innerHTML = '<iframe src="http://domain.com/feeds/'+id+'/'+size+'/" id="frame"></iframe>';
if(window.data){
clearInterval(timer);
data();
}
}
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-latest.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
timer = setInterval(tryData, 100);

Where are you passing the parameters?
Try this:
timer = setInterval(function(){
tryData(131, 'large');
}, 100);

Related

Redirect to differnent URL and load a javascript file

I am working on a project - When the URL to my site (www.mywebsite.com), is entered, I want it to go automatically go to a different website in the same browser window and then go another website (www.anotherWebsiteOne.com) in the same and the after X seconds will load another webSite (www.anotherWebSiteTwo.com) in the same browser, and so on.
I would like everytthing to stay in the same browser window
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Basic Javascript Example</title>
<script type="text/javascript" src="webSites.js"></script>
</head>
<body onload="start()">
</body>
</html>
and my webSites.js:
var webSites = [
'http://www.anotherWebPageOne.com/',
'https://www.anotherWebPageTwo.com/',
'http:www.anotherWebPageThree.com/',
];
var iTarget;
function nextTarget(){
window.open( targets[iTarget], 'target' );
if( ++iTarget >= targets.length ) {
iTarget = 0;
}
}
function start() {
iTarget = 0;
nextTarget();
setInterval( nextTarget, 5000 );
}
start()
you can use :
<body onload="start()">
</body>
or you can simply add start() to the end of your js file
just add start() to end of your webSites.js file
whatever in your js file will be executed automatically and you have to just call the start function in the js file by invoking it.
also, rename your webSites variable to targets.
in your JS file you just need to add window.onload = <Your Function Name>;
eg:-
var webSites = [
'http://www.anotherWebPageOne.com/',
'https://www.anotherWebPageTwo.com/',
'http:www.anotherWebPageThree.com/',
];
var iTarget;
function nextTarget(){
window.open( targets[iTarget], 'target' );
if( ++iTarget >= targets.length ) {
iTarget = 0;
}
}
window.onload = nextTarget;
function start() {
iTarget = 0;
nextTarget();
setInterval( nextTarget, 5000 );
}
I hope it will solve your problem

Firefox not executing scripts loaded dynamically via another external script

I've been having trouble with Firefox not executing JavaScript files that were loaded dynamically via an external script.
Let me explain.
I have the following HTML file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Restive.JS</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="assets/js/load.js"></script>
</head>
<body>
<h1>Loading JavaScript</h1>
</body>
</html>
Inside my load.js file, I have the following code:
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test1.js', 'assets/js/test2.js'];
for (var i = 0; i < list_arr.length; i++) {
loadScript(list_arr[i]);
}
});
And inside test1.js and test2.js, I have console.log('test1.js is loaded!'); and console.log('test2.js is loaded!');.
The problem is that test1.js and test2.js are loaded (I can see both files in the <head> via inspection), but they are never executed (because no messages appear in the console log).
However, when I change the format of script reference in my original HTML by inlining the JavaScript i.e. changing from this:
<script type="text/javascript" src="assets/js/load.js"></script>
to this:
<script>
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test3.js', 'assets/js/test4.js'];
for (var i = 0; i < list_arr.length; i++) {
console.log('i = ' + i);
loadScript(list_arr[i]);
}
});
</script>
Then the scripts are loaded and executed.
I don't see this behaviour in Chrome or Safari, only Firefox. Also, inlining is not an option because this functionality is built-in to a library that users will have to reference via an external link.
Is this a problem that is fixable?
EDIT
I'm on a Mac OSX 10.10.5 using Firefox 46.0.1

Web form javascript image refresh with interval

Please help me to refresh periodically an image in a web form (asp.net).
Here is my code. The image is not refreshing. Thank you in advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.11.0.min.js">
$(document).ready(function () {
var refreshId = setInterval(function () {
var obj = document.getElementById("<%=Image1.ClientID%>");
var src = obj.src;
var pos = src.indexOf("?");
if (pos >= 0) {
scr = src.substr(0, pos);
}
var date = new Date();
obj.src = src + '?v=' + date.getTime();
return true;
}, 10000);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/sOverview.png" />
</div>
</form>
</body>
</html>
and the code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Image1.ImageUrl = Image1.ImageUrl + "?" + DateTime.Now.ToLongTimeString()
End Sub
A script element gets its script from either the text node inside it, or the URL of the src attribute. Not both.
If you want to load two scripts (one from a URL and on in the text node) then you need two script elements.

How to get access to iframe element

I have the following html and javascript. If I click on simulate event I want the HandleEvents function to post the text into the 'child' page html. So I am essentially trying to latch onto an html element inside a child web page from a parent.
How do I do that?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function _bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
function doconfigure() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="configure.html";
}
}
function doevents() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
}
function dooutbound() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="outbound.html";
}
}
function HandleEvents(data) {
//post data to show_events.html page
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
//post to events field
var elem = top.frames['display'].document.getElementById('event');
if(elem) {
elem.innerHTML = data;
}
}
</script>
<title></title>
</head>
<body>
<fieldset>
<legend>Select</legend>
<input type="button" value="Configure" onclick="doconfigure();">
<input type="button" value="Events" onclick="doevents();">
<input type="button" value="Outbound" onclick="dooutbound();">
<input type="button" value="simulate event" onclick="HandleEvents('my event');">
<br />
</fieldset>
<iframe src="configure.html" name="display" id="ifrm" height="700" width="800">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
Then the show_events.html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<p>Events:</p>
<p id="event"></p>
</body>
</html>
You will not be able to do this unless the IFRAME shares the same origin as the parent script (for CSRF-protection purposes). If this requirement is met, it's all good.
jQuery is strongly recommended for this as things can get very, very messy very quickly.
You can gain access to the DOM of the IFRAME using the following:
jQuery (Fiddle: http://jsfiddle.net/ZYxVA/)
var myIFRAME = $("iframe#test");
var myContent = $("html",myIFRAME.contents());
Native (Fiddle: http://jsfiddle.net/L8Cek/)
var myIFRAME = document.getElementById("test");
var mC = myIFRAME.contentDocument,
mCbody = mC.getElementsByTagName("body")[0];
var docE = document.createElement("div");
docE.innerHTML = "this is a test";
mCbody.appendChild(docE);
As you can probably tell by now, jQuery is strongly recommended due to the fact that your code will get very hairy, very quickly otherwise. The quick run-down is, $("iframe").contents() allows you to get contentDocument. From there, you can run queries against that DOM by passing it as the second parameter.
In addition to this, you also will not be able to do anything until the iframe is fully loaded. You can listen to this by binding an onLoad event on it.
You need to wait for the iframe to be fully loaded before you can access the elements in the iframe.
Basic idea:
function HandleEvents (data) {
var myIframe = document.getElementById('ifrm');
myIframe.onload = function() {
var innerDoc = myIframe.contentDocument || myIframe.contentWindow.document;
var myElement = innerDoc.getElementById('event');
myElement.innerHTML = data;
};
myIframe.src = 'show_events.html';
}

how can you determine location of <script> tag from inside said tag?

I am trying to figure out the location of the script tag the current javascript is running in. What is really going on is that I need to determine from inside a src'd, dynamically inserted javascript file where it is located in the DOM. These are dynamically generated tags; code snippet:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>where am i?</title>
<script type="text/javascript" charset="utf-8">
function byId(id) {
return document.getElementById(id);
}
function create_script(el, code) {
var script = document.createElement("script");
script.type = "text/javascript";
script.text = code;
el.appendChild(script);
}
</script>
</head>
<body>
<div id="find_me_please"></div>
<script>
create_script(byId("find_me_please"), "alert('where is this code located?');");
</script>
</body>
</html>
You could give the script an id tag, like this dude does...
You can use document.write to create a dummy DOM object and use parentNode to escape out. For example:
<script>
(function(r) {
document.write('<span id="'+r+'"></span>');
window.setTimeout(function() {
var here_i_am = document.getElementById(r).parentNode;
... continue processing here ...
});
})('id_' + (Math.random()+'').replace('.','_'));
</script>
This assumes you don't actually have control of the <script> tag itself, such as when it's inside a <script src="where_am_i.js"></script> - if you do have control of the <script> tag, simply put an ID on it, as in:
<script id="here_i_am">...</script>
If you are just running this on page load, this works
<script>
var allScripts = document.getElementsByTagName('script');
var thisScript = allScripts[allScripts.length];
alert(thisScript);
</script>

Categories