views:

546

answers:

1

I have this sample page:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax Page</title>
<script type="text/javascript">
function ajax_hello() {
    alert ("hello"); 
}
alert ("Hello from JS");
</script>
</head>

<body>
This is the Ajax page.
<a href='#' onclick='ajax_hello();'>Click here to fire off JS function</a>.
</body>
</html>

I am calling it with this:

new Ajax.Updater($(element), page, { method: "get", evalScripts: true });

The alert is running, but the function is not registering (ajax_hello()).

Is there a way to get ajax to register a javascript function to the calling page?

+3  A: 

In response to the comment, I poked at the documentation and it appears that there are some special rules for Prototype when scripts are evaluated by the updater. The scripts can be anywhere in the response, but you need to assign any function definitions to a global variable to make them available to your page.

About evalScripts and defining functions If you use evalScripts: true, any block will be evaluated. This does not mean it will get included in the page: they won't. Their content will simply be passed to the native eval() function. There are two consequences to this:

The local scope will be that of Prototype's internal processing function. Anything in your script declared with var will be discarded momentarily after evaluation, and at any rate will be invisible to the remainder of the page scripts. If you define functions in there, you need to actually create them, otherwise they won't be accessible to the remainder of the page scripts. That is, the following code won't work:

// This kind of script won't work if processed by Ajax.Updater:
function coolFunc() {
    // Amazing stuff!
}

You will need to use the following syntax:

// This kind of script WILL work if processed by Ajax.Updater:
coolFunc = function() {
   // Amazing stuff!
}
tvanfosson
Then explain "the alert is running."
Jonathan Feinberg
@Jonathan -- it appears that it's handled differently, but there are some special considerations. I've updated.
tvanfosson
makes sense since this in effect overrides any previous functions named coolFunc(). Thanks!
OneNerd