ColdFusion 8: CFAjaxProxy
We've all heard of the cool new Ajax stuff in ColdFusion 8, particularly the UI stuff. But I haven't seen many people mention CFAjaxProxy. This tag is basically a simple way to communicate with a CFC from the client using JavaScript. In the past I'd normally use a library like ajaxCFC to accomplish this, and we may still need those libraries. They may do a lot more than the stuff offered by CFAjaxProxy. Anyway, here's a simple echo demo with CFAjaxProxy.
This is your cfm page:
<cfajaxproxy cfc="echo" jsclassname="respond">
<html>
<head>
<script type="text/javascript">
function getResponse() {
//grab the name from the field
var name = document.getElementById('name').value
//initiate the proxy with a local var
var r = new respond()
//define the response function
r.setCallbackHandler(displayResponse)
//define the error handler
r.setErrorHandler(errorHandler)
//call the echo function from the CFC
r.echo(name)
}
function displayResponse(resp) {
document.getElementById("responseArea").innerHTML = resp
}
// Error handler for the asynchronous functions
function errorHandler(statusCode,statusMsg) {
alert(statusCode+': '+statusMsg)
}
</script>
</head>
<body>
<input type="text" id="name" size="10">
<input type="button" value="Tell name" onclick="getResponse()"><br />
<span id="responseArea"></span>
</body>
</html>
Put this code in a file and save it as echo.cfc, in the same folder as the cfm:
<cffunction name="echo" access="remote" returnFormat="json" output="false">
<cfargument name="inputTxt" type="String">
<cfset inputTxt = "Hi "&inputTxt&", how are you?">
<cfreturn inputTxt>
</cffunction>
</cfcomponent>
This will basically take the name you type in the text field, and respond with "Hi {name}, how are you?" Very simple, but it shows the basic functionality available with CFAjaxProxy.
CFAjaxProxy uses JSON for it's data transfer format. You can set the proxy to use either Asynchronous (default) or Synchronous communication.
Jake Munson
36 Yrs old