Forum Moderators: open

Message Too Old, No Replies

Execute JavaScript function after AJAX loaded

         

lologin

5:04 pm on Nov 15, 2006 (gmt 0)

10+ Year Member



at the page i have:

<div id="ajax">
</div>

after AJAX load the content of the div becomes:

<div id="ajax">
<script language="JavaScript" type="text/javascript">
alert("test");
</script>
</div>

why alert("test"); is not called? i am sure that div content is loaded ok.

bwstyle

9:49 pm on Nov 15, 2006 (gmt 0)

10+ Year Member



Rather than have your javascript populate a div that has more javascript in it, why don't you just call the extra javascript commands after you populate the div?

For example in the flow of your script:

$('ajax').innerHTML='my new content';
alert('test');

lologin

9:40 am on Nov 16, 2006 (gmt 0)

10+ Year Member



because each time i need to execute different javascript function.
is there a possibility to create a JavaScript function from the text loaded via AJAX and to execute it? (assume i have var functionText that contains a string 'function a() {alert("a");}')

Robin_reala

1:50 pm on Nov 16, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could get the contents of the script node and then run eval() on it, but eval's slow and a security risk.

Ideally, you'd not be sending back functions with XMLHTTPRequest but just data.

lologin

12:16 pm on Nov 18, 2006 (gmt 0)

10+ Year Member



thanks. i already got throw. i send the content of JavaScript function. and execute it with eval();

crazyadmin

7:54 pm on Dec 6, 2006 (gmt 0)

10+ Year Member



In what way would using eval() be a security risk if you have exclusive control over the file directory and contents? Did you have in mind any exploits or bugs or did you simply have in mind a situation where someone would be able to upload his own files to the server?

As for the speed or slowness of the eval() function, I assume that would completely depend on the string size. If you include just a few lines of JavaScript inserted inside short conditioned statements then the returned data size and the corresponding CPU workload when processing the data should be negligable. I assume using eval() in this manner doesn't require any additional server requests, just local CPU processing...

Anyway, if there is any other cross-browser compatible solution than this one (not involving temporary database or file storage) to execute AJAX generated JavaScript I'd very much like to know...