Ask a Jedi: Using ColdFusion Ajax to set Client Variables

James Brown (yes, him) asks:

Is there a way to assign a value to a client variable using JavaScript? I know JavaScript runs on the client side and ColdFusion on the server, but with AJAX allowing remote calls to ColdFusion I wonder if it might be possible. Thank you for your help.

Yep, and it’s so easy, it’s rather trivial. As long as you can make a HTTP request with Ajax, then you can run any code you would imagine. I’ve been blogging about jQuery pretty extensively lately so let’s do this one just using what ships in ColdFusion 8. First, I’ll create a simple form:

<form> Set Name: <input type="text" name="name" /> <input type="button" value="Set" id="btn" /> </form>

Next I’ll use the cfajaxproxy to bind to the name form field.

<cfajaxproxy bind="url:setname.cfm?name={name}">

This simply says: Generate JavaScript that watches for a change to the name value and pass it to the url: setname.cfm?name={name}, where {name} will be the value of the form field. The tag also allows you to run CFC methods or JavaScript functions. setname.cfm is simply:

<cfparam name="url.name" default=""> <cfset client.name = url.name>

And that’s it. You may want to change when the Ajax call is made. By default it is fired with the onBlur event. So if you click the set button, or anything else on the page, the Ajax call is made. You could modify things a bit and tell it to fire just on the button click:

<cfajaxproxy bind="url:setname.cfm?name={name@none}&{btn@click}">

This bind expression means: Pass name, but don’t monitor it (none), and monitor the btn button’s click event. Why is there a & between the two binds? I needed a valid URL for the request and the bind has to actually be in the URL itself. Not quite as obvious and simple as the first example, but it gives you a bit more control by running just when the button is clicked.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. 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.

Lafayette, LA https://www.raymondcamden.com

Comments