Evaluating Script blocks loaded from AJAX with Prototype

I'm working with protoype at the moment and here's a little gotcha I found when loading html snippets via ajax which contain script blocks. For example loading:

<script language="javascript" type="text/javascript">
   function sayHi(){
      alert('Hi');
   }
</script>
<input type="button" value="Click Me" onclick="sayHi()"/>

By default, prototype will not evaluate the script block so when you load this via an Update or Request call, clicking the button will result in a error.

To resolve this you need to do two things:

  • Add the 'evalScripts:true' parameter to the update request
  • Change the format of the functions as shown below

evalScripts : true

new Ajax.Updater('targetid',
   'http://www.example.com/myurl',
   { method: 'get', evalScripts: true });

Change the format of the functions:

<script language="javascript" type="text/javascript">
   sayHi = function(){
      alert('Hi');
   };
</script>

<input type="button" value="Click Me" onclick="sayHi()"/>

The way this get evaluated will make the functions exist correctly so that they can be called.

Many thanks to Sergio Pereira for this article on prototype that explained the problem.

Cheers, Mark

Comments
BlogCFC was created by Raymond Camden. This blog is running version 5.1.004.