ColdFusion Ajax leading zeros issue

This post is more than 2 years old.

A user posted a question to my forums that I thought would make for interesting blog matter. It concerns ColdFusion, binding, and results with leading zeros. I touched on this before (Interesting ColdFusion 8, AutoSuggest issue to watch for) so this may be something folks are aware of already. Here is some background. Imagine a CFC with this simple method:

<cffunction name="getKey" access="remote" returnType="string"> <cfreturn "001234"> </cffunction>

Notice the result is a number, but with zeros in front. If you bind this to something on the front end:

<cfdiv bind="cfc:test.getkey()" />

You will only see 1234, not 001234. If you inspect the HTTP call with Firebug, you can see that the server returned 1234.0. ColdFusion took care of dropping the .0 at least, but this is not a desirable result. As mentioned in the earlier blog post, this seems to be the nature of the JSON serialization in ColdFusion. I can think of two simple ways around this.

One way would be to bind to a JavaScript function that then used cfajaxproxy to call the back end. Your back end cfc would need to prefix the result so the zeros aren't dropped. Like so:

<cffunction name="getKey2" access="remote" returnType="string"> <cfreturn "pre" & getKey()> </cffunction>

My problem with this solution is that your mucking with your model code. You shouldn't need to do that. Luckily there is another way to handle this. Don't forget that CFCs (in ColdFusion 8 at least) support a plain return format. Plain meaning "don't do squat to my result, just return it!". So if I change my cfdiv to:

<cfdiv bind="url:test.cfc?method=getkey&returnformat=plain" />

It works as expected now. I'm still using my CFC, but I've switch to the URL format. It's a bit more verbose, but at least my model CFC isn't changed.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA