Returning Multiple Value Elements to ColdFusion Remote Method via jQuery AJAX

Lets say I have a select element that supports multiple selected values:

<form>
<select id="mySelect" multiple size="3">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>

I wish to return this information to my ColdFusion CFC that contains a remote method via AJAX:

$.ajax({
	type: 'POST',
	url: 'myCFC.cfc',
	dataType: 'JSON',
	data: {
		'method':'myMethod',
		'value':$('mySelect').val()
	}
});

My CFC method looks like:

<cffunction name="myMethod" access="remote" output="false">
	<cfargument name="value" required="true" type="string">

	<cfset local.myVar = arguments.value>
	<!--- more logic --->
</cffunction>

This solution will error out due to the fact that the key “value” passed via AJAX is actually passed as “value[]”. Note the appended brackets denoting an array. I can’t reference “#arguments.value[]#” as this tries referencing an array and “#arguments[‘value[]’]#” is not allowed.

I tried all sorts of ways to try and get at that key value in the method. The only way I could come up with was to reference the argument via an index such as “arguments[1]”. But my real code was too complex to rely upon this method.

Another way was to append “.toString()” call the the end of the “val()” call when retrieving the values selected. This converts the array of values to a comma-delimited string of values. However this method will not allow the use of commas.

What I ended up doing was inserting some logic to convert any arrays into a pipe-delimited list. It’s not the best solution in the world but I think it’ll work.

var thisVal = $(this).val();
if ($.isArray(thisVal))
	var thisValRtn = thisVal.join("|");
else
	var thisValRtn = thisVal;

$.ajax({
	type: 'POST',
	url: 'myCFC.cfc',
	dataType: 'JSON',
	data: {
		'method':'myMethod',
		'value':thisValRtn
	}
});

If you have a better method than this, I’d love to hear about it.