Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing and returning ColdFusion Structure via JQuery

I have a ColdFusion session variable that's a structure of data. My goal is to execute a jQuery call that does one of two things via Ajax:

  1. sends that ColdFusion structure to a ColdFusion component method, updates an element of that structure with a newly created string, and returns that same structure back.

or

  1. executes a ColdFusion component method that creates a new string, returns that string, and assigns that new string to an element of that same ColdFusion session structure after the Ajax call.

I would think it'd be easy, but I've been having some problems. Anybody know what I would need to do?

like image 378
user1100412 Avatar asked Mar 02 '12 22:03

user1100412


1 Answers

Well, the CF session structure and jQuery operate in two different spheres - CF on the server and jQuery in the browser. In order to "send that ColdFusion structure to a [cfc]..." from Ajax, you'll have to have serialized the session structure as a json string and then transmitted that json string to the client somehow. Most likely, you'll want to do this as part of the rendering of the page to the client:

<cfoutput>var jsonStruct = #SerializeJSON(session.myStruct)#;</cfoutput>

Then you can use the jsonStruct variable from your jQuery code as needed (as a real JS object). When you need to send it back to CF, you can serialize it again on the Javascript side, like so:

$.ajax({
   url: "foo.cfc?method=myMethod", 
   dataType: "json",
   data: {myStruct: JSON.stringify(jsonStruct)}, 
   success: function (respJSON) {
      jsonStruct = respJSON;
   }
});

Note that you should include json2.js to do the serialization, since some browsers coughIEcough don't support JSON.stringify() natively.

Update

I've updated the example jquery code to show how you can update the javascript object to use the response from the CFC. To work properly, your CF will need to look something like this:

<cffunction name="myMethod" access="remote" returnFormat="json">
  <cfargument name="myStruct" type="string">

  <cfset var realStruct = DeserializeJSON(arguments.myStruct)>

  <cfset session.myStruct = realStruct><!--- or whatever you want to do with it at this point --->

  <cfreturn session.myStruct>
</cffunction>
like image 115
Jake Feasel Avatar answered Oct 06 '22 00:10

Jake Feasel