0

Example function:

function myFunction() {
  alert("Test");
}

myFunction();

This will run fine when called in a normal HTML webpage. But if this is part of the innerHTML content that is returned from an AJAX call, the function call myFunction(); won't work.

For example, if the content of a div TestDiv is changed via AJAX, and the innerHTML contains the following:

<span>AJAX Result</span>
<script language="JavaScript">myFunction();</script>

This code will not work when the AJAX request is complete. How can this be fixed?

reformed
  • 4,505
  • 11
  • 62
  • 88
  • 2
    We can't help if you don't show how you're handling the AJAX response – Ian Jul 29 '13 at 21:45
  • possible duplicate of [jQuery: Evaluate script in ajax response](http://stackoverflow.com/questions/2158075/jquery-evaluate-script-in-ajax-response) – cmbuckley Jul 29 '13 at 21:45
  • Scripts don't get run when you insert them with `.innerHTML`. You have to create a script node explicitly. If you use jQuery's `.load()` method, it will take care of this for you. – Barmar Jul 29 '13 at 21:51

1 Answers1

1

Call your function in the success method on the ajax request.

$.ajax({
   url: 'your url',
   data: { data: data},
   success: function(data) {
      // Your function
      myFunction();
   }
});

btw if you're using html5, the type is no longer needed on the script tag

<script></script>

otherwise it's

<script type="text/javascript"></script>
Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94