There's no such thing as a stupid question, but they're the easiest to answer.
JoinTour
Login
 
Tag Cloud
access audio avg avg 8 bios blue screen boot bsod computer connection cpu crash css dell desktop dma driver drivers dvd email error excel explorer firefox firefox 3 freeze gimp graphics hard drive hardware hijackthis hjt install internet internet explorer itunes keyboard laptop macro malware monitor motherboard network networking outlook outlook 2003 outlook 2007 outlook express pio problem problems router seo server slow sound sp3 spyware trojan usb video virtumonde virus vista vundo windows windows vista windows xp winxp wireless
Software Development
Search
Search in:
 
Advanced Search
Tech Support Guy Forums > Software & Hardware > Software Development >
using a variable from a page in external script


HELLO AND WELCOME! Before you can post your question, you'll have to register -- it's completely free! Click here to join today! We highly recommend that you print a copy of our Guide for New Members. Enjoy!

 
Thread Tools
derektech's Avatar
Junior Member with 15 posts.
 
Join Date: Nov 2007
06-Nov-2007, 11:01 AM #1
using a variable from a page in external script
I need to use a value defined on a webpage in an external javascript file.

<html>
<body>
<script src="myscript.js"></script>


<Script Language="JavaScript">

var theVar = 'theValue';
</Script>

</body>
</html>

I need to be able to use theVar in the external javascript file called "myscript.js".

The challenge is that theVar is defined after the external script is called - the order of the calls must not be changed.

Therefore within "myscript" I have defined a function that loops until theVar has been defined in the html document.

See below for the code I have tried to use to achieve this from "myscript.js".
Should it work? If not can you point out where I may be going wrong?


====================================

function TestVariable(){
if(typeof theID != "undefined") {
break;

}
else{
setTimeout("TestVariable();", 300);
}
}

TestVariable();
=================

In addition, if it is possible, I would like to use the value of the captured variable to construct a dynamic url within the external file.

Ideas leading to a solution very much appreciated.

cheers
Mikrondel's Avatar
Member with 49 posts.
 
Join Date: Jun 2005
Location: Australia
Experience: Budding Genius
06-Nov-2007, 06:23 PM #2
As far as I know,
setTimeout("TestVariable();", 300);

makes TestVariable get called later, in a different context. Let's assume your code gets to the setTimeout line. This line will be executed, but then execution keeps on going, to the next }, and then the last }, then the function ends and execution continues on past the
TestVariable();
call that started the function off.

But, even if you end execution of the script right after setTimeout, when TestVariable gets called 300ms later, it's called by the Javascript engine, not your script. I.e. when it returns, your script won't resume, and the whole exercise is pointless.

Furthermore, I think Javascript is single-threaded only so supposing external script is busy-looping while waiting for the inline script to define theVar, the inline script will never run.

The question that really arises here is why you need the scripts to be executed in that order. Sure if you need the external script to do something beforehand, do so by all means, but then why not define a function in it that the inline script calls once it defines theVar?

If you're worried about preserving variables and such, that's a significantly simpler issue and we'll help you with that if need be.
Shadow2531's Avatar
Distinguished Member with 2,629 posts.
 
Join Date: Apr 2001
06-Nov-2007, 06:29 PM #3
You just want something like this?

Code:
<script id="external_example">
    function readyToGo() {
        alert(theVar);
    }
</script>
<script>
    var theVar = 'theValue';
</script>
<script>readyToGo();</script>
derektech's Avatar
Junior Member with 15 posts.
 
Join Date: Nov 2007
07-Nov-2007, 04:47 AM #4
thanks for the responses. Maybe I can elaborate further:

A variable has been defined on html webpage, and I want to use this variable in an external javascript (which script is also called within the html page). However the script is called before the variable is defined on the page. But I need to use the value variable (which is only to be found on the html page) to construct a dynamic url within the external script. But I cannot do this until after the lines on the html webpage that define and assign a value to the variable have been executed.

But since the order is that the external script is called before the lines on the html page define and assign a value to the variable, I somehow need to test and ensure that the value of the variable is present before I can use it in the external script to construct the dynamic url - otherwise an exception will be thrown if I attempted to use it in the external script.

The code fragment on the html webpage looks like:
==================

<html>
<body>
<script src="myscript.js"></script>


<Script Language="JavaScript">

var theVar = 'theValue';
</Script>

</body>
</html>

============================

my test in the external script to ensure theVar has been defined and assigned a value, and so can use it to construct the dynamic url looks like:

====================================
//function to test the
function TestVariable(){
if(typeof theVar != "undefined") {
break;

}
else{
setTimeout("TestVariable();", 300);
}
}

TestVariable();

// from here construct dynamic url with the captured value in the html
.
.
.
=================
Shadow2531's Avatar
Distinguished Member with 2,629 posts.
 
Join Date: Apr 2001
07-Nov-2007, 06:52 AM #5
mypage.html
Code:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="myscript.js"></script>
        <script>var theVar = "zipzambam";</script>
    </head>
    <body>

    </body>
</html>
myscript.js
Code:
var interval = setInterval(readyToGo, 1000);
function readyToGo() {
    if (!theVar) {
        return;
    }
    clearInterval(interval);
    alert(theVar);
}
derektech's Avatar
Junior Member with 15 posts.
 
Join Date: Nov 2007
07-Nov-2007, 07:06 AM #6
Should the first line be instead?

var interval = setInterval(readyToGo(), 1000);
Shadow2531's Avatar
Distinguished Member with 2,629 posts.
 
Join Date: Apr 2001
07-Nov-2007, 07:30 AM #7
No. The first argument to setInterval is a reference to the function to call.

In other words, it wants to know what function to call so *it* can do readyToGo(), when it's ready.

You can look at it this way:

Code:
var readyToGo = function() {
    if (!theVar) {
        return;
    }
    clearInterval(interval);
    alert(theVar);
};
var interval = setInterval(readyToGo, 1000);
derektech's Avatar
Junior Member with 15 posts.
 
Join Date: Nov 2007
07-Nov-2007, 08:35 AM #8
techguy ROCKS!!! Simply the best. My very first problem solved in no time.

thumbs up!!!
derektech's Avatar
Junior Member with 15 posts.
 
Join Date: Nov 2007
07-Nov-2007, 10:34 AM #9
I have realised that the dynamic url needs to be within an iframe. So I tried to use document.write in the external script to write the iframe with the captured variable back into the page. When i did this, the page loading loops forever. When I viewed source there is nothing at all in it (a completely blank page source).


if (window.theVar !="undefined")
{
//use the variable to construct a dynamic url
document.write("<IFRAME SRC='someurl;value=' + theVar + '?' + 'WIDTH=200 HEIGHT=150 FRAMEBORDER=0></IFRAME>'");
.
.
.

}

Any ideas how I should do this. Is it possible to use document.write to achieve this, or rather should I be considering some different approach?

cheers
Shadow2531's Avatar
Distinguished Member with 2,629 posts.
 
Join Date: Apr 2001
07-Nov-2007, 11:00 AM #10
Avoid document.write for this. It will actually create a new page and won't append the iframe to the current document.

You can do it like this:
Code:
var readyToGo = function() {
    if (theVar && document.body) {
        clearInterval(interval);
        var iframe = document.createElement("iframe");
        iframe.setAttribute("src", "http://www.google.com/");
        iframe.setAttribute("width", "200");
        iframe.setAttribute("height", "150");
        iframe.setAttribute("frameborder", "0");
        document.body.appendChild(iframe);
    }
};
var interval = setInterval(readyToGo, 1000);
In this case though, I'm assuming you want to append it to the end of the body. If not, you want to wait till the element you want to append to is present (along with theVar) and append to that element instead.

If you do indeed want to wait till document.body is present and append to that, you might as well forget about the setInterval stuff and in your script just do:

Code:
window.onload = function() {
    // do whatever you need to.
};
, unless you have something on the page that delays the load event for a long time.
__________________
10 ? "a line as the unending horizon"
20 ? "a curve as the rolling hillside"
30 ? "a point as a distant bird"
40 ? "a ray as the rising sun"
run

Last edited by Shadow2531 : 07-Nov-2007 11:12 AM.
derektech's Avatar
Junior Member with 15 posts.
 
Join Date: Nov 2007
08-Nov-2007, 07:53 AM #11
Beautiful stuff.
I am hooked to this site!!!!
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are Off
Refbacks are Off

You Are Using:
Server ID
Advertisements do not imply our endorsement of that product or service.
All times are GMT -4. The time now is 09:50 AM.
Copyright © 1996 - 2008 TechGuy, Inc. All rights reserved.
Powered by vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Powered by Cermak Technologies, Inc.