Ajax and Coldfusion
by Chris, 09/12/2017
Coldfusion and Ajax work great together. Long past are the days of pages refreshing to grab data.
The following is a simple cfc that returns some user info in json format with a type of query.
<cfcomponent> <cffunction name="getUsers" access="remote" returnformat="json" returntype="query"> <cfquery name="data" datasource="ds"> select username, address, birthday from employees; </cfquery> <cfreturn data/> </cffunction> </cfcomponent>
The next step is to grab the column information passed back from Coldfusion and then map it to the data object supplied.
$.ajax({
type: "GET",
url: "cfc/data.cfc?method=data",
returnformat: "json",
error: function(res) {alert('some error');},
success: function(res) {
var sampleArray = [];
var resultSet = $.parseJSON(res);
var columnMapping = {};
//add our column values to our mapping object
for (var i = 0; i < resultSet.COLUMNS.length; i++) {
columnMapping[resultSet.COLUMNS[i]] = i;
}
//loop through the data object and get the corresponding value as it maps to the column.
//for this example, we will add the query row to an array and then dump the output.
$.each(resultSet.DATA, function (index, item) {
//Coldfusion returns fields in caps.
sampleArray.push({
username: item[columnMapping.USERNAME],
address: item[columnMapping.ADDRESS],
birthday: item[columnMapping.BIRTHDAY]
});
});
console.log(sampleArray);
}
});
That's it! You now have an array of objects from coldfusion.