473,396 Members | 1,871 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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.XMLHttpRequest) {
oXmlRequest = new XMLHttpRequest();
oXmlRequest.open("GET", sURL, bAsync);
oXmlRequest.send(null);
}
/* branch for IE/Windows ActiveX version */
else if (window.ActiveXObject) {
oXmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
oXmlRequest.open("GET", sURL, bAsync);
oXmlRequest.send();
}

return oXmlRequest;
}

function EvalScriptFile(oDocument){
if (oDocument){

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

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

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



//this works:
eval("alert('hello');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 3381
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.XMLHttpRequest) {
oXmlRequest = new XMLHttpRequest();
oXmlRequest.open("GET", sURL, bAsync);
oXmlRequest.send(null);
}
/* branch for IE/Windows ActiveX version */
else if (window.ActiveXObject) {
oXmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
oXmlRequest.open("GET", sURL, bAsync);
oXmlRequest.send();
}

return oXmlRequest;
}

function EvalScriptFile(oDocument){
if (oDocument){

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

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

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



//this works:
eval("alert('hello');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(fileName)
{ var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.src = fileName;
document.getElementsByTagName('head')[0].appendChild(scr);
}

--
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.javascript 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.ActiveXObject) {
oXmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
oXmlRequest.open("GET", sURL, bAsync);
oXmlRequest.send();
}
Why not set an onreadystatechange handler to inform you when the
request is done (when asynchroneous)?

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


But does this work?
---
function LoadScriptLiteral() {
eval("alert('hello');function test(){ alert('test'); };");
}
EvalScriptLiteral();
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 LoadScriptLiteral, 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(){return 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/rasterTriangleDOM.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
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!


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.ActiveXObject) {
oXmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
oXmlRequest.open("GET", sURL, bAsync);
oXmlRequest.send();
}


Why not set an onreadystatechange 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 oScriptFileRequest = RequestDocument(sURL,false);
EvalScriptFile(oScriptFileRequest);
} ....
//this works:
eval("alert('hello');function test(){ alert('test'); };");
test();


But does this work?
---
function LoadScriptLiteral() {
eval("alert('hello');function test(){ alert('test'); };");
}
EvalScriptLiteral();
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 LoadScriptLiteral, 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(){return 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(fileName)
{ var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.src = fileName;
document.getElementsByTagName('head')[0].appendChild(scr);
}


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
Razzbar escribió:
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.


If JS don't work, my sites fallback to the fact that they don't support
client-side scripting, then many browsers will be supported only because
of this.

Regards,

knocte

--
Jul 23 '05 #11
VK escribió:
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...


Actually, I think the feature should be just called "HttpRequest",
because nothing prevents me for getting anything I want with the Http
protocol using this.

Regards,

knocte

P.S.: Perhaps you should suggest to the responsible for DOM specs to
delete the accessibility to the ".responseText" attribute. That way
you'll be able to dictate how the technologies must be used.

--
Jul 23 '05 #12
VK
> Actually, I think the feature should be just called "HttpRequest",
because nothing prevents me for getting anything I want with
the Http protocol using this.


"Who can stop Hafiz from likening a ladybug to the Padishah"
An old Persian proverbe ;-)

<http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/f6ce0a5e95d8bf30/ba5264709e33894e?q=group:comp.lang.javascript+auth or:VK&rnum=19&hl=en#ba5264709e33894e>

Jul 23 '05 #13

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

Similar topics

3
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...
8
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 =...
3
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...
24
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...
7
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...
1
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...
1
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?...
1
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...
13
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.