mike chambers | about

Example loading data from a data base into Flash MX with Flash Remoting and CF MX

Monday, April 29, 2002

Below is sample code that shows how to load data from a data base from Flash MX using Flash Remoting and ColdFusion components.
Download and install the ColdFusion MX preview release.
Download and install the Flash Remoting Addons for Flash MX.
You can download the files here.
First create a new ColdFusion component, name it DbTest.cfc and save it in wwwroot\com\macromedia\dbtest
Here is the component code:

<cfcomponent>
 <cffunction name="getData" access="remote" returntype="query">
  <!- CompanyInfo is a DSN name for an example DB that CFMX sets up by default ->
<cfquery datasource="CompanyInfo" name="result">
select * from Employee
</cfquery>
  <cfreturn result />
 </cffunction>
</cfcomponent>

Open Flash, and place a Combo Box component on the stage, and give it an instance name of “dataBox”
add the following ActionScript to the first frame of the Flash movie:

#include "NetServices.as"
#include "NetDebug.as"
/** we will use an instance of the Result class to capture
the data from the server **/
Result = function()
{
}
/** onResult is called when data is loaded from the server.
In this case, a RecordSet object will be passed to it **/
Result.prototype.onResult = function(rs)
{
trace("Data Received : " + rs.getLength() + " rows.");

//data box is a simple combo box on the stage.
dataBox.setDataProvider(rs);
}
/** onStatus is called if any errors occur when communicating
with the server **/
Result.prototype.onStatus = function(error)
{
trace("Error : " + error.description);
}
/** set the location of the Flash Remoting gateway **/
NetServices.setDefaultGatewayURL("http://localhost:8500/flashservices/gateway");
var gw = NetServices.createGatewayConnection();
/** get a reference to the service on the server
First param is the path to the service on the server
Second param is the object to send the server response too **/
var server = gw.getService("com.macromedia.dbtest.DbTest", new Result());
/** call the remote method **/
server.getData();

Save your Flash movie, and test. You should see all of the data displayed in the combo box. If it is formatted weird, then make the combo box wider.
If you get any errors, open the NetConnection Debugger (Windows > NetConnection Debugger) and then retest your movie. This will show all of the communication between Flash and the server.
This is just a simple example, but shows how easy it is to do some pretty complex stuff in Flash MX with Flash Remoting.

twitter github flickr behance