using coldfusion structures in javascript

There are situations where we need to use data returned from a coldfusion function  to be used in javascript. For example in some ajax operations we need the data returned from coldfusion to be used in javascript. We will see how this is done.

Below is a CFC function that returns a structure with some data:-

<cffunction name=”myTestFunction” access=”remote” returntype=”Any”>

<cfargument name=”myTestArgument” required=”yes” type=”string”>

<cfset DataStruct = StructNew()>

<cfset DataStruct.DataOne = “First Data”>

<cfset DataStruct.DataTwo = “Second Data”>

<cfset DataStruct = serializeJSON(DataStruct)>

<cfreturn DataStruct>

</cffunction>

Here we are filling a Structure with datas that are going to be used in javascript. In order to use in Javascript we are converting our structure DataStruct to JSON(Javascript Object Notation) format by the inbuilt CF function serializeJSON.

Now in our Javascript function that receives the response of the coldfusion function after the ajax function, we need to add the following code:-

var ResponseStructure = ColdFusion.JSON.decode(Response);

Here the “Response” from the coldfusion is stored into our JS variable  ResponseStructure by the inbuilt ColdFusion.JSON.decode function for CF. Now the variable ResponseStructure contains the structure DataStruct that is returned from Coldfusion. The key-value pair inside the structure can be accessed by calling like this:-

var myDataOne =  ResponseStructure.DATAONE;

var myDataTwo  =  ResponseStructure. DATATWO;

Note that the key names of the structure should be specified in CAPITAL letters. Also make sure that we have imported the required AJAX libraries for doing this in  our page:-

<cfajaximport>

Advertisements

1 Comment (+add yours?)

  1. Stephan
    Jan 19, 2013 @ 03:36:30

    Oh my goodness! Incredible article dude! Thanks, However
    I am experiencing troubles with your RSS. I don’t know the reason why I cannot join it. Is there anyone else getting similar RSS problems? Anyone who knows the solution will you kindly respond? Thanks!!

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: