Alex Rivera | Logout

How can I send an array variable to a ColdFusion CFC remote method via ajax using jQuery?

Asked 2010-10-22T17:17:18.327
11

I have a ColdFusion CFC function like this:

<cffunction access="remote" name="getResults"
    returntype="struct"
    returnformat="JSON"
    output="no">

    <cfargument name="q" required="true" type="array" />

...
</cffunction>

How do I call this function from jQuery? Neither form of array encoding by jQuery will get ColdFusion to see the value as array.

If you pass "q=a&q=b" (like with jQuery.ajaxSettings.traditional = true), the function will get the string "a,b", not an array. While splitting on comma may seem like a possibility, it will not work if one of the "q" values contains a comma. Also, ideally, the function on the server-side should not have to be aware of the problems of how to serialize the data over the wire, and should continue to take in an array.

If you pass "q[]=a&q[]=b" (the jQuery default), it will not map over to the "q" parameter. If you try to change the name of the "q" parameter to "q[]", the CFC will error out due to an invalid parameter name.

Edit
Report

1 Answer

6

Investigating this problem, I found the following blog post: http://www.coldfusionjedi.com/index.cfm/2010/3/23/Using-jQuery-to-post-an-array-to-a-ColdFusion-Component - This suggested encoding the array as a JSON string, and then deserializing it inside the CFC method, with the unfortunate impact of requiring the CFC function to have to change to deal with JSON.

So I investigated further, and here's the best solution I have found so far.

By looking at the HTTP calls made when using cfajaxproxy, I discovered that you can send a single argumentCollection parameter as a JSON string to call the remote CFC method.

So the client side call looks something like this (using jquery-json plugin to do the serialization):

var params = {q: ['a', '1,2,3']};

$.getJSON('My.cfc?method=getResults', {argumentCollection: $.toJSON(params)}, function(data) {
// handle data
});
answered 2010-10-22T17:22:47.780

Your Answer