Search code examples
javascriptajaxprototypejs

How to execute Javascript function defined in main window from within Ajax response


I have Javascript function defined in the main index.html file.
One part of this page is updated using Ajax (with prototype.js). Attempt to execute Javasript function defined in the main file from within returned AJAX code fails.
evalScripts: true option in Ajax.Updater prototype.js function does not help.
How do I fix this? Thank you in advance.

This is my index.html file:

<html>
<head>
<script src="js/lib/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
    function foo(x) {
        alert(x);
    }

    function loadContent() {
      new Ajax.Updater('responseArea', 'response.php' , { evalScripts: true } );
    }
</script>
</head>

<body>
    <div id="main">
        <span style="cursor: pointer" onclick="loadContent();">Click on me to call Ajax response</span><br>
        <br></br>
    </div>

    <div id="responseArea">
        This will be replaced with Ajax response
    </div>
</body>
</html>


This is response.php:
  <?php
         echo '<span style="cursor: pointer" onclick="foo("foo Called from within Ajax response");">
             Click on me to call foo from within Ajax response</span>';
   ?>

Solution

  • Since evalScripts is true, you can put any JS snippet in your response and it will be executed when the AJAX call completes:

    <script type="text/javascript">
    foo("foo Called from within Ajax response");
    </script>
    

    If you don't want to execute, but just want to include more JS, you can insert a regular JS include tag:

    <script type="text/javascript src="yournewcode.js"></script>
    

    This is better than including the JS inline because it allows the browser to cache the file.