Bind Json Data To Dropdown List Using Ajax Call with ColdFusion
We always write examples of code whenever we notice two things.. 1. that many people are asking the question and 2. that there are no good examples out there for people to use.
What we are looking to do here is simple. Make an Ajax call using a CFC and bind it to a Select Dropdown. Let's get right to the coding.
Your CFC should look as follows:
- <cffunction name="getStates" output="no" access="remote" returnformat="json" hint="Returns ALL States">
<cftry>
<cfquery datasource="#application.dsn#" name="qryStates" >
SELECT stateID, StateName
FROM tblStates
ORDER BY StateName
</cfquery>
<cfset response = [] />
<cfloop query="qryStates">
<cfset obj = {
"STATEID" = StateID,
"STATENAME" = StateName
} />
<cfset arrayAppend(response, obj) />
</cfloop>
<cfset result = #serializeJSON(response)# >
<cfreturn #result#>
<cfcatch>
<cfinclude template="../err_handler.cfm">
</cfcatch>
</cftry>
</cffunction>
Simple enough. A few points on the CFC... Make sure your access is remote instead of the defaul public. All data being accessed by an Ajax call must be this way. We've tried adding a returntype of 'struct' or 'array' or even 'string' but we sometimes get failures and so we just don't include it.
We are creating the loop to get a properly formatted json object - although some of the newer ColdFusion Json features may do the same thing. We know this one works and so we're sticking with it.
The body of your HTML will look as follows:
<select id="myStates"></select>
<script>
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://www.someurl.com/filename.cfc",
dataType: "json",
data: {
method: "getStates"
},
success: function (data) {
var appenddata;
$.each(data, function (key, value) {
appenddata += "<option value = '" + value.StateID + " '>" + value.StateNAME + " </option>";
});
$('##myStates').html(appenddata);
}});
</script>
</cfoutput>
That's all folks. The myStates near the bottom has a double pound because it is a reference to an ID field and we need the literal pound to stay there when it is rendered by the browser.
Hope you find this extremely helpful in your projects and be sure to like us on Facebook if we helped your cause.
- Poster's Profile
Support Services
Member since: 01/12/2015
Total Posts: 3
Total Post Replies: 1
Total Posts Liked: 1
Total Likes Received: 3
Reply to:
Bind Json Data To Dropdown List Using Ajax Call with ColdFusion
No Replies Yet