Ask Ben: Converting Javascript Variables Into ColdFusion Variables

Posted June 22, 2009 at 9:51 AM by Ben Nadel

Tags: ColdFusion, Javascript / DHTML, Ask Ben

How can I convert a JavaScript variable into a coldfusion variable?

I have been asked this question enough times that I figured it was be time to turn it into an actual Ask Ben blog post for future reference. Often times, when front-end developers start getting into server-side scripting (hopefully using ColdFusion), there is some confusion as to where the various parts of the page rendering work flow are executing. And, because of this confusion, developers get stuck trying to access one part of the work flow from another.


 
 
 

 
ColdFusion Executes On The Server - Javascript Executes On The Client (Web Browser).  
 
 
 

To clear up the confusion, I think you just need to step back and understand the request-response processing work flow:

  1. The server gets a request to deliver some content (at the given URL).
  2. The server constructs the response (in our case, an HTML page containing Javascript).
  3. The server returns the HTML data to the client (Web Browser).
  4. The data streams from the Server to the Client.
  5. The browser renders the response (HTML page) for the user at which time any embedded Javascript code executes.

Once we hit step #4, the ColdFusion server is no longer involved. In step #5, when the client renders the HTML response, it doesn't even have to know where the HTML data came from. As such, when the Javascript executes in step #5, it has no knowledge of nor any access to the ColdFusion portion of the page response work flow - these two points of execution happen at different times on different machines.

Javascript can, however, communicate with the ColdFusion server by making AJAX-based page requests. These HTTP requests are viewed by the ColdFusion server as completely new page requests by the client and do not have access to temporary ColdFusion variables created during previous requests (unless those variables were explicitly cached on the server).

So, the moral of the story is that you can't really turn a Javascript variable into a ColdFusion variable because the two are completely unrelated. Once you understand the page request / response work flow, this becomes obvious. If you want Javascript to send values back to the ColdFusion server for further processing, you can only do so via AJAX requests. I hope that this clears up some confusion.



Reader Comments

Jun 22, 2009 at 9:13 PM // reply »
1 Comments

You can always write to a hidden form field if you are processing a form, etc.


Jun 23, 2009 at 12:56 AM // reply »
34 Comments

Great Post

When you are calling your JavaScript you can always have the included JavaScript file end in a .cfm which would help in some cases... This will allow you to load different content based on variables that you pass... you can always pass variables through JavaScript like so...

<script type="text/javascript"
src="javascript.cfm?var1=bob&var2=frank">
</script>

This essential will pass the variables to coldfusion in which you can convert the variables into coldfusion variables using the url variable... I have used this method a few times but I don't recommend it for really robust applications.


Jun 23, 2009 at 1:37 AM // reply »
1 Comments

What about <cfwddx action="cfml2js" ... />?
Sure, we can't use ColdFusion vars on the client side, but we can serialize them and return to the browser along with the rest of the JavaScript code.


Jun 23, 2009 at 4:59 AM // reply »
1 Comments

json format is very helpfull to pass variables between javascript and coldfusion in ajax calls. There are 2 coldfusion functions since cf8 DeserializeJSON() and SerializeJSON().
And from you javascript code you can serialize your JS variables to a json string by using the json serializer( http://www.JSON.org/json2.js ).


Jun 23, 2009 at 6:06 PM // reply »
10,743 Comments

@Jody,

Definitely true - a great technique.

@Alexey,

Yeah - using ColdFusion variables to help render the Javascript that ultimately gets executed by the browser is definitely some we can do, and is the easier of the two directions (server to client vs. client to server).

@Patrick,

JSON rocks! 'nuff said.


Nov 28, 2010 at 2:22 AM // reply »
2 Comments

Hey Jody can i get a practical example of what u have suggested.

Thanks in advance..


Nov 28, 2010 at 8:14 PM // reply »
10,743 Comments

@Shailesh,

What @Jody is talking about is basically getting a CFM file to "serve" up a Javascript file. Since it's a CFM file, it will push any query-string-based variables into the URL scope. So, for example, if you had the following script block:

<script src="scripts.cfm?foo=bar"></script>

... then you could have a CFM file (scripts.cfm) that looked like this:

  • <cfoutput>
  • var myJavascriptValue = "#url.foo#";
  • </cfoutput>
  •  
  • <cfcontent type="text/javascript" />

As you can see, our Javascript file content is generated by ColdFusion. Then, we use the CFContent tag to tell the browser that this file being rendered is actually a "Javascript" file, not an HTML file.


Nov 29, 2010 at 11:53 AM // reply »
2 Comments

@Ben,

Thanks Ben for a detailed explanation.. :)


Dec 5, 2010 at 3:15 PM // reply »
10,743 Comments

@Shailesh,

Any time my friend.


Jan 19, 2011 at 7:26 AM // reply »
2 Comments

if i am including a y.cfm file in page x.cfm via <script>, how do i print a variable which is in y.cfm file on the x.cfm page or y.cfm page?


fco
Mar 2, 2011 at 12:47 PM // reply »
1 Comments

Ben...cannot one use the ToScript function. From the cfml 9 pdf reference page 1276-1279:

"This function can convert ColdFusion strings, numbers, arrays, structures, and queries to JavaScript or ActionScript syntax that defines equivalent variables and values."

..."Usage:
To use a ColdFusion variable in JavaScript or ActionScript, the ToScript function must be in a cfoutput region and be surrounded by number signs (#). For example, the following code uses the ToScript function to convert a ColdFusion variable to a JavaScript variable:

<cfset thisString="hello world"> <script type="text/javascript" language="JavaScript">
<cfoutput> var #toScript(thisString, "jsVar")#;
</cfoutput>
</script>

When ColdFusion runs this code, it sends the following to the client:
<script type="text/javascript" language="JavaScript"> var jsVar = "hello world";
</script>"

So it seems the ColdFusion ToScript function allows communicate of variables between CF9 and Javascript/Actionscript and in both directions.


Nov 23, 2011 at 9:19 PM // reply »
1 Comments

Hi All,
it might a liltle too late... :)
but i have problem with javascript and coldfusion.
I have a 'Process' button on my CF and that button create a JavaScript 'alert' which is has value Yes/No.
If i choose Yes, then CF will run codes to update a table but if I choose No then CF will only show the table content.
So how is it the CF get the value Yes or No from JS.
I'm new comer in CF and not familiar with JavaScript (:( ),soo please help me with detail example for the solution of my problem.

Thanks all...

Regards,


PJ
Jan 19, 2012 at 7:36 PM // reply »
5 Comments

Thank you SO much! Wish I'd found this before a long time in google... funny how many of the answers I finally find end up being on your blog. ;-)

I want to get the html page (or window) height in order to set the framed height of a cflayout bound tab. Apparently the only way you can get this info is through javascript (e.g. jquery), but then there's no way to automatically get the info back to CFML in order to have it set a variable for the tab height. So either my tabs (already a double-scroll in most 'lists' cases) have a scrollbar that go way off the page which is not properly functional, or, people with 21" monitors have what looks like about 3.5 inches of content near the top of their screen. (If I don't define the height, CF appears to default to giving me what looks like about 20 pixels...)

Do you know of any solution to this?

PJ


Mar 28, 2012 at 3:00 AM // reply »
1 Comments

@fco,

I "think" that toScript is one-way: from CF to JS. I don't think it can go the other way (from JS to CF).



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 16, 2012 at 8:18 PM
Best Of ColdFusion 10 Contest Entry - HTML Email Utility
Just found this, looks good! I'm trying to run it on local, it's the 64bit version and I'm experiencing horrible lag. On average the generate.cfm processes the content change in 60-90 seconds. I've ... read »
May 16, 2012 at 6:40 PM
Maintaining Sessions Across Multiple ColdFusion CFHttp Requests
I am trying to integrate this CFHTTPsession into an application that will log into zeekrewards.com to post ads and I am not having any luck. The code works perfectly for logging into other websites, ... read »
May 16, 2012 at 2:44 PM
Creating A Sometimes-Fixed-Position Element With jQuery
Thank you, very useful technique! Worked like a charm. ... read »
May 16, 2012 at 1:58 PM
Movies As A Religious Experience
Acting can, in a way, ruin the movie-goer's experience. I used to be able to get so caught up in movies and their plots, and totally engaged. But lately, I haven't been able to as much with a lot o ... read »
May 16, 2012 at 1:52 PM
The Science Of Optimal Post-Exercise Nutrition
children of this age eat very less vegetables so u can opt for salads they will like it also carrot ,cucumber,onion and as far as pulses are concerned u can boil them ,give him along with mashed rice ... read »
May 16, 2012 at 1:34 PM
Strange ColdFusion JRUN Stack Overflow Error
Hey, Recently I updated my jrun4 using the latest updater 7 and now i am having memory issues :(:(:( any help is appreciated ... read »
May 16, 2012 at 9:56 AM
ColdFusion 10 Beta, Apache Tomcat, And Symbolic Links On Mac OSX
Hi, Now that ColdFusion 10 is out I have stumbled over this as well and I cannot figure out the proper solution. We're running virtual hosts via Apache2; the ColdFusion-applications store their fil ... read »
May 15, 2012 at 6:03 PM
Movies As A Religious Experience
@Ben, I don't know whether you'd consider this a religious observation, but it seems to me, in a sense, movies multiply how many lives we get to have. Each movie is like a little extra life we get ... read »