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:
or
I would think it'd be easy, but I've been having some problems. Anybody know what I would need to do?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With