473,569 Members | 2,721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using eval for contents retrieved with XMLHttpRequest( )

Hello.

I have always thought that the eval() function was very flexible and
useful. If I use it, I can define functions at runtime!!

However, I have found a case where eval() does not work properly. It
works, for example, when invoking functions (alert('hello') ), but not
for defining functions.

The case occurs when retrieving the javascript code with
XMLHttpRequest( ). It fails on Mozilla/Firefox and IE!

I will quote the code:

<script>
function RequestDocument (sURL, bAsync) {
var oXmlRequest;

/* branch for native XMLHttpRequest object */
if (window.XMLHttp Request) {
oXmlRequest = new XMLHttpRequest( );
oXmlRequest.ope n("GET", sURL, bAsync);
oXmlRequest.sen d(null);
}
/* branch for IE/Windows ActiveX version */
else if (window.ActiveX Object) {
oXmlRequest = new ActiveXObject(" Microsoft.XMLHT TP");
oXmlRequest.ope n("GET", sURL, bAsync);
oXmlRequest.sen d();
}

return oXmlRequest;
}

function EvalScriptFile( oDocument){
if (oDocument){

/* only if status shows "loaded" */
if (oDocument.read yState == 4) {

/* only if "OK" */
if (oDocument.stat us == 200) {
eval(oDocument. responseText);
}
else if (oDocument.stat us == 404) {
alert("File not found");
}
}
}
}

function LoadScriptFile( sURL){
var oScriptFileRequ est = RequestDocument (sURL,false);
EvalScriptFile( oScriptFileRequ est);
}



//this works:
eval("alert('he llo');function test(){ alert('test'); };");
test();

//but, if I put on a file (called mylib.js and located at the same
//dir as this file on the web server), the following contents:
// alert('hello2') ;
// function test2(){ alert('test2'); };
//
LoadScriptFile( "mylib.js") ;
test2();
//the first alert is called (hello2)! but debugger says
//that test2 is not defined!
// what happens??
</script>
Do anybody know why?? Thanks in advance.

Regards,

Andrew

--
Jul 23 '05 #1
12 3418
knocte wrote:
Hello.

I have always thought that the eval() function was very flexible and
useful. If I use it, I can define functions at runtime!!

However, I have found a case where eval() does not work properly. It
works, for example, when invoking functions (alert('hello') ), but not
for defining functions.

The case occurs when retrieving the javascript code with
XMLHttpRequest( ). It fails on Mozilla/Firefox and IE!

I will quote the code:

<script>
function RequestDocument (sURL, bAsync) {
var oXmlRequest;

/* branch for native XMLHttpRequest object */
if (window.XMLHttp Request) {
oXmlRequest = new XMLHttpRequest( );
oXmlRequest.ope n("GET", sURL, bAsync);
oXmlRequest.sen d(null);
}
/* branch for IE/Windows ActiveX version */
else if (window.ActiveX Object) {
oXmlRequest = new ActiveXObject(" Microsoft.XMLHT TP");
oXmlRequest.ope n("GET", sURL, bAsync);
oXmlRequest.sen d();
}

return oXmlRequest;
}

function EvalScriptFile( oDocument){
if (oDocument){

/* only if status shows "loaded" */
if (oDocument.read yState == 4) {

/* only if "OK" */
if (oDocument.stat us == 200) {
eval(oDocument. responseText);
}
else if (oDocument.stat us == 404) {
alert("File not found");
}
}
}
}

function LoadScriptFile( sURL){
var oScriptFileRequ est = RequestDocument (sURL,false);
EvalScriptFile( oScriptFileRequ est);
}



//this works:
eval("alert('he llo');function test(){ alert('test'); };");
test();

//but, if I put on a file (called mylib.js and located at the same
//dir as this file on the web server), the following contents:
// alert('hello2') ;
// function test2(){ alert('test2'); };
//
LoadScriptFile( "mylib.js") ;
test2();
//the first alert is called (hello2)! but debugger says
//that test2 is not defined!
// what happens??
</script>
Do anybody know why?? Thanks in advance.

Regards,

Andrew

Why would you use XMLHttpRequest to load a script? Following does an
adequate job and does not require the use of eval

loadScript(file Name)
{ var scr = document.create Element('script ');
scr.type = 'text/javascript';
scr.src = fileName;
document.getEle mentsByTagName( 'head')[0].appendChild(sc r);
}

--
Vladdy
http://www.klproductions.com
Jul 23 '05 #2
Don
However, this sort of logical approach to injecting or inserting
javascript dynamically does NOT work in the latest version of Safari.

Jul 23 '05 #3
Don wrote:
However, this sort of logical approach to injecting or inserting
javascript dynamically does NOT work in the latest version of Safari.


Does the XMLHTTPRequest object "work" in Safari?
If not, then its a moot point.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #4
Don
Yes (most of the time).

My errors with Safari have nothing to do with javascript insertion but
getting anything (e.g. HTML) from ASP code using ajax. I keep getting
errors, even after req.readyState == 4 where the req.status is
undefined, the statusText is undefined, and the responseText is null.
My code all works fine with Firefox and Netscape (and IE using the
ActiveX object). The only way I can make the errors go away is by
making the ajax calls synchronous rather than asynchronous, so I have
to check for a Safari browser and set the synch flag appropriately.

As for the dynamic javascript problem, Apple admits (a posting in one
of the Apple groups) that it is different from other browsers in this
way (they saw the js insertion functionality as a security issue) but
still want to do what other browsers are capable of doing.

Jul 23 '05 #5
knocte <kn****@NO-SPAM-PLEASE-gmail.com> writes:
I have always thought that the eval() function was very flexible and
useful.
I feel the same way about flamethrowers :)
If I use it, I can define functions at runtime!!
What can you do with "eval" that you can't do with one or more
function expressions?

Working with syntax at runtime is ... volatile. Just like
flamethrowers :)
However, I have found a case where eval() does not work properly.
Not according to specification or not as you would want it to work?
It works, for example, when invoking functions (alert('hello') ), but
not for defining functions.
.... but you said above that ... ? :P
The case occurs when retrieving the javascript code with
XMLHttpRequest( ). It fails on Mozilla/Firefox and IE! I will quote the code:
Actual code and platform where it fails, as well as a description of
the error later ... a good error report :) Keep it up!

Have you tried any other browser?
<script>
Use valid HTML. That way you can be sure that it's not the HTML that
causes your problems. In this case:
<script type="text/javascript">
function RequestDocument (sURL, bAsync) {
var oXmlRequest;

/* branch for native XMLHttpRequest object */ .... else if (window.ActiveX Object) {
oXmlRequest = new ActiveXObject(" Microsoft.XMLHT TP");
oXmlRequest.ope n("GET", sURL, bAsync);
oXmlRequest.sen d();
}
Why not set an onreadystatecha nge handler to inform you when the
request is done (when asynchroneous)?

Anyway...
function LoadScriptFile( sURL){
var oScriptFileRequ est = RequestDocument (sURL,false);
EvalScriptFile( oScriptFileRequ est);
} ..... //this works:
eval("alert('he llo');function test(){ alert('test'); };");
test();


But does this work?
---
function LoadScriptLiter al() {
eval("alert('he llo');function test(){ alert('test'); };");
}
EvalScriptLiter al();
test();
---

It doesn't work, because the content is evaluated in the same scope as
the call to eval. That means that the declaration of test() happens
inside the function LoadScriptLiter al, and can't be seen outside of
it.

You have the same problem, because you call "eval" inside
LoadScriptFile.
One soultion would be to let the script declare its variables as
global variables:

var global = (function(){ret urn this;})();
global.test2 = function() { alert("test2"); }

Not as pretty, but guaranteed to work.

I can't find a better way of doing it right now, but I'll keep
pondering :)

Good luck!
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6
Hello. Thanks for your answer!

Lasse Reichstein Nielsen escribió:
I have always thought that the eval() function was very flexible and
useful.
I feel the same way about flamethrowers :)


Are you saying that I wanted to throw a flame?
If I use it, I can define functions at runtime!!


What can you do with "eval" that you can't do with one or more
function expressions?


I can run code that comes from an external source, for example.
Hey, I know the disadvantages of eval(), I was just commenting its
advantages.
Working with syntax at runtime is ... volatile. Just like
flamethrowers :)
I don't understand what you mean.

However, I have found a case where eval() does not work properly.


Not according to specification or not as you would want it to work?


Well, I actually didn't know.

It works, for example, when invoking functions (alert('hello') ), but
not for defining functions.


... but you said above that ... ? :P

Excuse me? :?
The case occurs when retrieving the javascript code with
XMLHttpReques t(). It fails on Mozilla/Firefox and IE!

I will quote the code:


Actual code and platform where it fails, as well as a description of
the error later ... a good error report :) Keep it up!


Well, if I say it fails on Mozilla/Firefox, I think the error is
platform-independent...
Have you tried any other browser?
No. I usually work with Mozilla or Firefox (because they respect
standards) and I do some tests later with IE (for compatibility).
<script>


Use valid HTML. That way you can be sure that it's not the HTML that
causes your problems. In this case:
<script type="text/javascript">


Well, thanks for your advice but I think here it is irrevelant; above
all, because I have used this "short" way so as not to paste unnecessary
things to the list. It's just an example.
function RequestDocument (sURL, bAsync) {
var oXmlRequest;

/* branch for native XMLHttpRequest object */

...
else if (window.ActiveX Object) {
oXmlRequest = new ActiveXObject(" Microsoft.XMLHT TP");
oXmlRequest.ope n("GET", sURL, bAsync);
oXmlRequest.sen d();
}


Why not set an onreadystatecha nge handler to inform you when the
request is done (when asynchroneous)?


Because I am using synchronous mode in this case. I don't need it.
Anyway...
function LoadScriptFile( sURL){
var oScriptFileRequ est = RequestDocument (sURL,false);
EvalScriptFile( oScriptFileRequ est);
} ....
//this works:
eval("alert(' hello');functio n test(){ alert('test'); };");
test();


But does this work?
---
function LoadScriptLiter al() {
eval("alert('he llo');function test(){ alert('test'); };");
}
EvalScriptLiter al();
test();
---

It doesn't work, because the content is evaluated in the same scope as
the call to eval. That means that the declaration of test() happens
inside the function LoadScriptLiter al, and can't be seen outside of
it.

You have the same problem, because you call "eval" inside
LoadScriptFile.


Yes, you got it. I doesn't have many experience with
javascript/ecmascript and I thought that, as well as for this language
the scope inside an "if" is the same as the one outside, it would happen
the same with functions, but I was wrong.
One soultion would be to let the script declare its variables as
global variables:

var global = (function(){ret urn this;})();
global.test2 = function() { alert("test2"); }

Not as pretty, but guaranteed to work.

I can't find a better way of doing it right now, but I'll keep
pondering :)

Good luck!
/L


Hey, I find this way very useful to allow external functions access to
the global scope! Thanks very much for your comments.

Andrew

--
Jul 23 '05 #7
Vladdy escribió:
Why would you use XMLHttpRequest to load a script? Following does an
adequate job and does not require the use of eval

loadScript(file Name)
{ var scr = document.create Element('script ');
scr.type = 'text/javascript';
scr.src = fileName;
document.getEle mentsByTagName( 'head')[0].appendChild(sc r);
}


Thanks for your suggestion, but I prefer to use XMLHttpRequest this
time, for many reasons:

- I can control better when the javascript is evaluated, because I don't
delegate this task to the browser.
- I can do it synchronously, so as to wait until the file called is
loaded before loading more javascript code.
- I will be able to use this method even with bad-formed HTML documents
(for example, those without a head tag).

Regards,

Andrew

--
Jul 23 '05 #8
VK
> The case occurs when retrieving the javascript code with
XMLHttpRequest( ). It fails on Mozilla/Firefox and IE!


Actually XMLHTTP doesn't stay from "get XML or HTTP or whatever you'll
get in your head". It stays from "get XML data for HTML environment
(browser)". But I'm affraid that all hell broke loose already. Mr.
Knocte is getting his JavaScript this way, someone already tried to get
binary data stream. So soon I guess we'll see XMLHTTP used to download
music, pictures and "Star Wars Episode 3". So shall be it...

Jul 23 '05 #9
So shall also be many users scratching their heads as their browsers
hang useless, because some cowboy figured that if you put your JS
functions on the server and use a synchronous call, you are guaranteed
they will come a'running ever time, and execute when you want them to,
not before.

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2424
by: vanisathish | last post by:
Hi I am running a client side javascript timer to periodically refresh the contents of some tables in the HTML page. The table values are dynmically binded from XML DOM object using the <XML tag in HTML>. The data is getting updated properly. but whenever the value is refreshed, the HTML page flickers. How do i avoid this flickering.. ...
8
2107
by: Jason Shohet | last post by:
I want to build a rules engine in a rules.xml page. I was thinking it would look like this: - Rules - rule1 if (0 < iTime <= .5) { iFee = 15; } - rule2 if (.5 < iTime <= 1) { iFee = 20; } - yada yada Now lets say in my c# code I loop thru the Rules node of rules.xml, and I want to evaluate each rule, given an iTime that the...
3
3067
by: Hitesh | last post by:
Hi, I am getting the response from another Website by using the HttpHandler in my current site. I am getting the page but all the images on that page are not appearing only placeholder are displayed. Can anybody know this issue and help me to resolve this. In past i received the response saying that i should download the image first...
24
3405
by: Larry | last post by:
Hi there: I have seen numerous postings about eval() and its evils on this forum. However, one of our developers is using it in the following way, which seems like a great use of it. Page makes Ajax request to ASP.Net web service. Web service does some data lookup and builds a string representation of a Javascript array which is then...
7
2993
by: | last post by:
I have what's probably a simple page lifecycle question related to dynamically evaluating values that are placed by a repeater and dynmically placing user controls that use those values. I'm attempting to bind a user control I've written, "ImageBox", to a repeater. The user control takes a custom property, "ContentID", that will execute...
1
14947
by: Pablo | last post by:
Dear all, I have a website where I need to fill its contents after retrieving some data from another system (not a DB, but you can think like it). I know the nature of the data, but the order that it is retrieved is random, and there is no way to order it. Therefore, it is giving me some pain to produce the html code. I was thinking of...
1
5290
by: Tarik Monem | last post by:
OK, I'm pretty sure this cannot work because I'm trying to use JavaScript (client-side) to write to an xml file (which is server-side) using XMLHttpRequest. Can I use PHP do what I'm trying to do? Here's my code: The function mySaveFunction() is called by clicking the "Update" button, after the user changes the data which is populated in...
1
3179
by: wenijah | last post by:
Hi everyone! First thank you for reading this post and yes, you probably already see that kind of topic title somewhere but the problem I've got today might be different than the 100 topics I've seen so far that did not resolve my problem... Environment and problem: I have a page A with Ajax.js and a <div id="ajx">Content</div> that changes...
13
3161
by: My Pet Programmer | last post by:
The way I usually set up and work with the XMLHttpRequest to execute server side functions and get results is this: var url = "someurl?params=" + params; var conn = createRequest(); // gets an XMLHttpRequest object conn.open("GET", url); conn.onreadystatechange = function () { if (conn.readyState == 4 && conn.status == 200) {
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7922
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8119
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7668
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5218
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1209
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.