Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 475
jrduncans Avatar asked Oct 22 '10 17:10

jrduncans


1 Answers

First thing to know is jQuery Ajax requests do not encode arrays so have you to use something else to encode the data (this is where jquery.JSON.js comes from referenced below). So with a the JSON encoded found there, I then figured out the correct syntax by working with cfajaxproxy and studying the URL it generates in Firebug:

http://localhost/remote.cfc?method=getResults&argumentCollection=%7B%22q%22%3A%5B1%2C2%5D%7D

Yes the "argumentcollection" approach is correct, and the variable "q" with a reference to an array is in there.

I used the following code as a test bed:

remote.cfc

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

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

        <cfreturn {a=1,b=2}>
    </cffunction>
</cfcomponent>

remote.cfm to see how cfajaxproxy generates its url

<cfajaxproxy cfc="Remote" jsclassname="Remote">
<cfoutput>
<script language="javascript" type="text/javascript">
var oRemote = new Remote();
alert(oRemote.getResults([1,2]));
</script>
</cfoutput>

remote.html doing it with jQuery

<script language="javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script language="javascript" src="jquery.JSON.js"></script>
<script language="javascript" type="text/javascript">
var argumentCollection = { q: [1,2] };
$.ajax({
    url:        'remote.cfc',
    data:       {
        method: 'getResults',
        argumentCollection: $.JSON.encode(argumentCollection)
    },
    success:    function(response) {
        alert(response);
    },
    dataType:   'json'
});

</script>
like image 115
orangepips Avatar answered Sep 20 '22 13:09

orangepips