Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 623
pbond Avatar asked Dec 09 '11 03:12

pbond


3 Answers

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);
like image 183
Adam Rackis Avatar answered Nov 10 '22 11:11

Adam Rackis


put you code in

$(document).ready(function()
{
  alert(msg);
});

or make use of readysatchange event of XMLHttp object.

XMLHttpobject.readyStateChange( furnction() { alert('msg'); } );

Edit

if you are using jquery than go for

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});

here in sucess event you can write your code which get executed once you are done with the ajax.

like image 1
Pranay Rana Avatar answered Nov 10 '22 11:11

Pranay Rana


any code inside body in between script tag will executed only while loading the document.

in ajax call,make use of callback or success: or oncomplete: to handle the ajax response if you are using jQuery.

like image 1
dku.rajkumar Avatar answered Nov 10 '22 12:11

dku.rajkumar