Wednesday, December 2, 2009

Javascript and ColdFusion

JavaScript changed my url variables.

I recently debugged a piece of old code that was doing some weirdness. In the code a JavaScript function was run after a combo box was changed. The function reloaded the same page with a few url variables. One of the url variables was changing when it reloaded. I found out JavaScript was calculating the numerical value and returning a different number, ( example: 027 became 17 ).

The original code looked something like this:
<code>
function recalcWeek()
{
var year=document.forms[0].slctFiscalYear.options[document.forms[0].slctFiscalYear.selectedIndex].value;
location.href="somePage.cfm?div_no="+<cfoutput>#url.div_no#</cfoutput>+"&event_id="+<cfoutput>"#url.Event_ID#"</cfoutput>+"&fiscal_year="+year;
}
</code>

The corrected code to fix the issue looked like this:
<code>
function recalcWeek()
{
var year=document.forms[0].slctFiscalYear.options[document.forms[0].slctFiscalYear.selectedIndex].value;
location.href="somePage.cfm?div_no=<cfoutput>#url.div_no#</cfoutput>&event_id=<cfoutput>#url.Event_ID#</cfoutput>&fiscal_year="+year;
}
</code>


The mistake was using the double quotes and the + to try and concatenate the values. ColdFusion will render the variable in the ## before JavaScript uses them so there is no need to concatenate. If you would do a view source on the page, or use Firebug, you would see the function after ColdFusion renders the variables and then the mistake becomes more obvious.

No comments: