Incorrect Variable Values in AjaxOnLoad

I just ran into another goofy Ajax problem with my ColdFusion apps. I have a page using a bound cfdiv to load a form. The form, once submitted, is supposed to take the value of a form field entered on the page and run an AjaxOnLoad event to use that value elsewhere. Here's a simple test to show what I mean.

First, create the main page, test.cfm:

<cfsilent>
   <cfajaximport tags="cfform" />
</cfsilent>
<html>
<head></head>
<body>
   <cfdiv bind="url:form.cfm" />
</body></html>

Now in form.cfm, add the following code:

<cfset myvar = 2 />
<cfif IsDefined("FORM.fieldnames")>
   <cfset myvar = FORM.testfield />
   <cfset ajaxOnLoad("testFunction") />
</cfif>
<cfoutput>
<script type="text/javascript">
testFunction = function(){
   alert('#myvar#');
}
</script>
</cfoutput>
<cfform>
   <cfinput name="testfield" value="#myvar#" />
   <cfinput type="submit" name="submitbutton" value="Submit Test" />
</cfform>

When you submit the form, you'll get the value 2 alerted. I thought I would try to be sneaky and add an if statement around the script so that it was only output when the value wasn't 2, like so:

<cfset myvar = 2 />
<cfif IsDefined("FORM.fieldnames")>
   <cfset myvar = FORM.testfield />
   <cfset ajaxOnLoad("testFunction") />
</cfif>
<cfif myVar NEQ 2>
<cfoutput>
<script type="text/javascript">
testFunction = function(){
   alert('#myvar#');
}
</script>
</cfoutput>
</cfif>
<cfform>
   <cfinput name="testfield" value="#myvar#" />
   <cfinput type="submit" name="submitbutton" value="Submit Test" />
</cfform>

That just caused a javascript error that it couldn't find the testFunction script. So this tells me that the script is rendered to the page when the div is first loaded, and it's not updated on subsequent div reloads. So my way around this is to put the new value into a hidden form field, and then use ColdFusion.getElementValue() to pick up the value for my testFunction.

Hope this saves someone else some frustration.

0 responses to “Incorrect Variable Values in AjaxOnLoad”

Leave a Reply

Leave this field empty:

Powered by Mango Blog.