Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Javascript loaded via AJAX [duplicate]

Possible Duplicate:
How do you execute a dynamically loaded JavaScript block?

I have seen many questions like mine here, but I didn't find an answer which is fitting for me.

I'm loading Code via AJAX, also including a script Tag including Javascript. As I already found out, this Javascript is not executed.

I also found out that eval() can help me, but as I'm a noob in Javascript and just need it for this one time, I have no idea where exactly to put it.

My PHP script is returning a string which I split with Javascript to put it into different parts of the page. This is working fine. One of the parts consists of this:

<div id=\"fb-root\"></div> <script>(function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) return;js = d.createElement(s); js.id = id;js.src = \"//connect.facebook.net/de_DE/all.js#xfbml=1\";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script>

Included like this:

document.getElementById("id").innerHTML=response1;

Where response1 is the variable where I have put the code from above after splitting the string. Anyone able to help me in a noob, easy way?

like image 756
Laura Avatar asked Aug 24 '26 07:08

Laura


1 Answers

You can use eval(). You have to give an ID to your script:

<script id='script'>
     some javascript
</script>

And then after loading your ajax response, for loading the script you add this line:

eval(document.getElementById('script').innerHTML);

Good luck!

like image 100
Guillaume le Floch Avatar answered Aug 25 '26 21:08

Guillaume le Floch