how do you execute a js script loaded with ajax

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bugboy
    New Member
    • Sep 2007
    • 160

    how do you execute a js script loaded with ajax

    I'm adding a script to a <div> element dynamically, after page load, via AJAX. My new script is just ignored.

    Ho do i get the script to execute when dynamically loaded?


    Code:
    <div id="a">
         <textarea id="'.$id.'">'.$text.'</textarea>
         <script type="text/javascript">event_listener("'.$id.'");</script>
    </div>

    Thanks!
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    You'll have to separate the JavaScript and either eval() it or dynamically include using script tags.

    Comment

    • bugboy
      New Member
      • Sep 2007
      • 160

      #3
      Thanks! I'm figuring out the eval thing... but i'm not sure what you mean by dynamically loaded with script tags, i'm replacing innerHTML with the <script> tags (see above) via ajax without luck.. does it need some type of handler function to register it once loaded, other than eval? not sure exactly what you mean.. i've read to avoid eval if you can...

      Thanks for you time!

      Comment

      • bugboy
        New Member
        • Sep 2007
        • 160

        #4
        I found your previous solution in another thread. The string i'm adding has js code which is determined during the request so it can't be added during first page load.. is your code added to the head during the ajax request too? else how would i get the new string too it?

        Code:
           1. var head = document.getElementsByTagName("head")[0];
           2. var script = document.createElement("script");
           3. script.type="text/javascript";
           4. script.appendChild(document.createTextNode(str)); //str is the string containing script
           5. head.appendChild(script);
        Like most things i'm sure this will become obvious once i understand!
        Thanks,

        Comment

        • acoder
          Recognized Expert MVP
          • Nov 2006
          • 16032

          #5
          Originally posted by bugboy
          is your code added to the head during the ajax request too?
          Yes. What part of the code do you not understand?

          Comment

          Working...