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?
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?
Share Improve this question edited Dec 28, 2011 at 21:56 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Nov 28, 2009 at 13:49 OneNerdOneNerd 6,55217 gold badges63 silver badges78 bronze badges 1- 1 How do you know it's not registering? Does the browser issue an error when you click the link? – Igor Zinov'yev Commented Nov 28, 2009 at 13:56
1 Answer
Reset to default 6In response to the ment, 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! }