Converting CFML Data to a JavaScript Object

The following example demonstrates the transfer of a CFQUERY result set from a CFML template executing on the server to a JavaScript object that is processed by the browser.

The application consists of five principal sections:

This example uses a registered ColdFusion 4.0 datasource and can be run from ColdFusion Server.

<!--- Create a simple query  --->
<CFQUERY NAME = 'q' DATASOURCE ='snippets'>
SELECT Message_Id, Thread_id,
Username, Posted from messages
</CFQUERY>

<script language=javascript>

<!--- Bring in WDDX JS support objects
A <script src=></script> can be used instead
wddx.js is part of the ColdFusion distribution --->
<CFINCLUDE template='/CFIDE/scripts/wddx.js'>

<!--- Use WDDX to move from CFML data to JS --->
<CFWDDX ACTION='cfml2js' input=#q# topLevelVariable='q'>

<!--- Recordset dumping routine --->
function dumpWddxRecordset(r)
{
// Get row count
nRows = r.getRowCount();

// Determine column names
colNames = new Array();
i = 0;
for (col in r)
{
if (typeof(r[col]) == "object")
{
colNames[i++] = col;
}
}

// Dump the recordset data

o = "Dumping recordset...<p>";

o += "<table cellpadding=3pt><tr>";
for (i = 0; i < colNames.length; ++i)
{
o += "<td>" + colNames[i] + "</td>";
}
o += "</tr>";

for (row = 0; row < nRows; ++row)
{
o += "<tr>";
for (i = 0; i < colNames.length; ++i)
{
o += "<td>" + r.getField(row, colNames[i]) + "</td>";
}
o += "</tr>";
}
o += "</table>";

// Write the table to the HTML stream

document.write(o);
}

<!--- Dump the recordset --->
dumpWddxRecordset(q);

</script>