Turn your CFC into a JavaScript Object (CF8 and Ajax)
One of my favorite new features of CF8 is the ability to create a JavaScript object from a CFC. You can then use the object to make Ajax calls. Here's a simple example that sends the results of checking an HTML check box into a CFC for processing...
The CFM file:
<cfajaxproxy cfc="mycfc" jsclassname="jsobj" />
<script language="javascript">
function checkmybox(cbox) {
var ischecked = 1;
// create the object
var cfcAsAjax = new jsobj();
if (!cbox.checked) {ischecked=0;}
// Call the CFC function as a JavaScript function
cfcAsAjax.setChecked(cbox.value,ischecked);
}
</script>
<input type="checkbox" value="1234" name="cbox1" onclick="checkmybox(this);" /> Add 1234 to my table.<br/>
<input type="checkbox" value="5678" name="cbox2" onclick="checkmybox(this);" /> Add 5678 to my table.
The CFC file (mycfc.cfc):
<cfcomponent displayname="mycfc" hint="CFC for example Ajax app">
<cffunction name="setChecked" access="remote">
<cfargument name="boxvalue" />
<cfargument name="ischecked" />
<cfset var addrecord = '' />
<cfset var deleterecord = '' />
<cfif arguments.ischecked>
<cfquery name="addrecord" datasource="#dsn#">
INSERT INTO mytable(boxvaluefield)
VALUES('#arguments.boxvalue#')
</cfquery>
<cfelse>
<cfquery name="deleterecord" datasource="#dsn#">
DELETE FROM mytable
WHERE boxvaluefield = '#arguments.boxvalue#'
</cfquery>
</cfif>
</cffunction>
</cfcomponent>
It's not an incredibly useful example as far as functionality goes, but it demonstrates how easy it is to create a JavaScript object from a CFC and use it for Ajax calls. You could replace the check box event with any JavaScript-triggered event. This same functionality could be achieved using a CFINPUT and the "bind" attribute, but there are many cases where your form (or other object) is not a CF element (example, input instead of cfinput).
Davis wrote on 09/05/07 6:07 PM
Thanks! I spent hours trying to figure out how to send a simple Ajax request!