pbond pbond - 1 month ago 10
Javascript Question

Javascript doesn't load after AJAX call

Ok the following HTML code is parsed when I load a page:

<div id="clip-wrapper">
<script type="text/javascript">
alert("bla");
</script>
</div>


This obviously leads to an alert saying "bla", after my AJAX call, the parsed HTML code looks like this:

<div id="clip-wrapper">
<script type="text/javascript">
alert("ajaxbla");
</script>
</div>


This on the other hand, doesn't result in an alert. Why? And how do I fix this?

Answer

If there are any scripts loaded into your dom from an Ajax call, they will not be executed for security reasons.

To get the script to execute, you'll need to strip it out of the response, and run it through eval

Ideally though, you'll want to run your script as a callback for when your ajax request completes. If you're using jQuery, this would be the success event of your ajax call, and if you're doing it natively, it would be the readyStateChange event of your xhr object.

EDIT

If you really want to opt for the eval option, you could try something like this:

document.getElementById(contentDiv).innerHTML = xmlHttp.responseText;
eval(document.getElementById("clip-wrapper").innerHTML);
Comments