Calling a CFC with multiple arguments using AJAX - ajax

I am using AJAX to call a CFC and I am trying to send over two variables from a query that I ran. My ajax looks like this:
$.ajax({
type:"POST",
url:"cfcs/get_equipment_details.cfc?method=getDetails",
dataType: 'json',
data: { equipment_name: "#equipment_name#", customer_name: "#customer_name#"},
cache:false,
success: function(response) {
console.log("Customer Name" + customer_name);
$.each(response.DATA, function(i, row){
var id = row[0];
var customer_name = row[1];
var equipment_name = row[2];
var date_last_completed = row[3];
var maintenance_interval = row[4];
var last_completed_by = row[5];
var equipment_notes = row[6];
var warranty_end_date = row[7];
var service_Tag = row[8];
var serial_number = row[9];
var backup_notes = row[10];
var TT = row[11];
$("##customer_name#id#").val(customer_name);
});
}
});
Here is my CFC:
<cffunction name="getDetails" access="remote" output="false" returntype="query">
<cfargument name="equipment_name" type="any" required="true">
<cfargument name="customer_name" type="any" required="true">
<!--- Get list of all equipment --->
<cfquery name="get_equipment" datasource="#datasource#">
select *
from equipment_maintenance
where equipment_name= <cfqueryparam value="#ARGUMENTS.equipment_name#" cfsqltype="cf_sql_varchar">
AND customer_name= <cfqueryparam value="#ARGUMENTS.customer_name#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfreturn get_equipment>
But my CFC is throwing an error:
The parameter customer_name to function getDetails is required but was
not passed in.
How can I successfully pass in those two argument and return my query results?

You are missing closing " for customer_name in your data attributes of Ajax function.
Your Ajax function should look something like this
$.ajax({
type:"POST",
url:"cfcs/get_equipment_details.cfc?method=getDetails",
data: { equipment_name: "#equipment_name#", customer_name: "#customer_name#"},
cache:false,
success: function(msg) {
$("##customer_name#id#").val(msg);
}
});
Now there is some issue with your cfc function. you are returning a variable that dose not exist and its same as your function name. If you do something like this it will work
<cffunction name="getDetails" access="remote" output="false" returnformat="JSON">
<cfargument name="equipment_name" type="any" required="true">
<cfargument name="customer_name" type="any" required="true">
<!--- Get list of all equipment --->
<cfquery name="get_equipment" datasource="#datasource#">
select *
from equipment_maintenance
where equipment_name= <cfqueryparam value="#ARGUMENTS.equipment_name#" cfsqltype="cf_sql_varchar">
AND customer_name= <cfqueryparam value="#ARGUMENTS.customer_name#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfreturn get_equipment.customer_Name>
</cffunction>
If you want entire query object to be return as you ajax response then parse JSON on success of ajax and process it further

Related

The parameter to the function is required but was not passed in

I am making a filter in order to drill down into a report. I have two fields that are dependent on the selection of another field (which is a multiselect list). When I make my selection(s) from that multiselect field, it looks like the parameter is being passed in as an array and ultimately not being recognized. It looks as if my parameter is being passed in as an array, which I'm thinking is the issue
Javascript Code:
function getMO()
{
var fa_code = $('#tslcFilterFA').val();
var ao_code = $('#tslcFilterAO').val();
var wq_code = $('#tslcFilterWQ').val();
var newOption = '';
$('#tslcFilterMO').empty();
$('#tslcFilterMO').append(newOption);
$('#TSLC_MO_Loading').css('display','inline');
$.ajax({
url: '../TSLC/getData.cfc',
type:"POST",
cache: false,
dataType: "text",
async:true,
data: {method: "getMO",
fa_code: fa_code,
ao_code: ao_code,
wq_code: wq_code
},
success: function(returnMsg)
{
try
{
var obj = JSON.parse(returnMsg);
$.each(obj.DATA, function(index,row) {
if (obj.DATA.length == 1)
{
var newOption = '<option selected="selected" value="' + row[0] + '">' + row[1] + '</option>';
}
else
{
if (row[2] == "1")
{
var newOption = '<option selected="selected" value="' + row[0] + '">' + row[1] + '</option>';
}
else
{
var newOption = '<option value="' + row[0] + '">' + row[1] + '</option>';
}
}
$('#tslcFilterMO').append(newOption);
});
try
{
$('#tslcFilterMO').multiselect('destroy');
}
catch(e) {}
$('#tslcFilterMO').multiselect({
selectedList: 4
}).multiselectfilter();
$('.ui-multiselect').css('width','225px');
$('#TSLC_MO_Loading').css('display','none');
}
catch(e)
{
alert('getMO Error parsing JSON');
}
},
error: function(httpRequest, textStatus, errorThrown)
{
alert("getMO status=" + textStatus + ",error=" + errorThrown);
}
});
}
I've tried to change this line:
var ao_code = $('#tslcFilterAO').val();
to this:
var ao_code = $('#tslcFilterAO').multiselect('getChecked').map(function () {return this.value;}).get();
I've also tried to wrap my ao_code variable in URLDecode() to see if it would pass the value as a string instead of an array, but neither works.
CF Code (from component):
<cffunction name="getMO" access="remote" returntype="any" returnformat="plain" hint="Get distinct Managing Orgs based on FA=ATT_IT and AO">
<cfargument name="fa_code" type="string" required="true">
<cfargument name="ao_code" required="true">
<cfargument name="wq_code" required="true">
<cfquery name="qMO" datasource="#request.dbdsn_ic4p#" username="#request.dbuser_m66266#" password="#request.dbpw_m66266#">
SELECT DISTINCT managing_org MANAGING_ORG, DECODE(managing_org,'*','*ALL*',managing_org) MANAGING_ORG_DISPLAY, DECODE(managing_org,'*',1,2) sortcol
<cfif #fa_code# NEQ "ATT_IT">
FROM HAS_TICKET_STATE_GUI_LOOKUP
WHERE client_id = '#fa_code#'
<cfelse>
FROM IT_TICKET_STATE_GUI_LOOKUP
WHERE 1=1
</cfif>
<cfif #ao_code# neq "">
AND active_org IN (<cfqueryparam value="#ao_code#" cfsqltype="cf_sql_varchar" list="true" />)
</cfif>
<cfif #wq_code# neq "">
<!--- !COM: is workaround for commas in listbox items! --->
AND work_queue IN (#replace(ListQualify(wq_code,"'",",","CHAR"),":COM!",",","all")#)
</cfif>
ORDER BY 3, 1
</cfquery>
<cfreturn serializeJson(qMO)>
</cffunction>
Change this line in your JS code
var ao_code = $('#tslcFilterAO').val();
to
var ao_code = $('#tslcFilterAO').val().join(",");
That should give you a list of string values from the multiple select field that you're expecting in your function in the CFC.
The join() method joins all elements of an array into a string. More on "join" here.
This article helped me solve my problem... https://christierney.com/2011/06/07/returning-multiple-value-elements-to-coldfusion-remote-method-via-jquery-ajax/
function getWQ()
{
var fa_code = $('#tslcFilterFA').val();
var ao_code = $('#tslcFilterAO').val();
if ($.isArray(ao_code))
var ao_code_array = ao_code.join(",");
else
var ao_code_array = ao_code;
var mo_code = $('#tslcFilterMO').val();
if ($.isArray(mo_code))
var mo_code_array = mo_code.join(",");
else
var mo_code_array = mo_code;
var newOption = '';
$('#tslcFilterWQ').empty();
$('#tslcFilterWQ').append(newOption);
$('#TSLC_WQ_Loading').css('display','inline');
$.ajax({
url: '../TSLC/cfcs/getData.cfc',
type:"POST",
cache: false,
dataType: "text",
async:true,
data: {method: "getWQ",
fa_code: fa_code,
mo_code: mo_code_array,
ao_code: ao_code_array
},
success: function(returnMsg)
{
Have you considered a combination of the jQuery serializeArray() function and the param() function? It creates a string similar to a query string which is easily parsed. You could send the whole form in.
Example: $.param($('#yourform').serializeArray(),false);
Or, perhaps, simply use the serializeArray function to send your function a JSON string?

Sort Struct in ColdFusion on Values ASC

How can I sort this structure by the values in ASC order?
<cfset dStruct = createObject("java", "java.util.LinkedHashMap").init()>
<cfquery name="gds" datasource="#application.dsn#">
SELECT * FROM stores WHERE region_id = #arguments.retailer_id#
ORDER BY client_loc ASC
</cfquery>
<cfoutput query="gds">
<cfset var dStru = { "#gds.storeid#" = "#gds.client_loc# - #gds.city#, #gds.state#" }>
<cfset StructAppend( dStruct, dStru )>
</cfoutput>
<cfset StructSort(dStruct,"textnocase","asc")>
....
<cfreturn SerializeJSON(dStruct) />
The results then populate a drop down. Here are the results:
struct
299 | ASH041 - ONTARIO, CA
300 | ASH042 - CLEARWATER, FL
301 | ASH044 - TAMPA, FL
302 | ASH046 - ORLANDO, FL
303 | ASH047 - SARASOTA, FL
304 | ASH048 - TAMPA, FL
305 | ASH002 - HUNTINGTON STN., NY
If it was sorting correctly, ASH002 would be the first result, but it appears to be sorting on the KEY instead of the VALUE. Is there a way to sort by the values?
I also tried this...
<cfset dStruct = createObject("java", "java.util.LinkedHashMap").init() />
Either way produces the same results. Here is a screenshot of the results...
Here is the jquery that populates the select menu.
$.ajax({
url: "/functions.cfc",
cache: false,
type: "get",
dataType: "json",
data: {method: "getstoresbyretailer", retailer_id: (retailer_id)}, //get stores
success: function (data) {
var $select = $('#storeid');
$select.find('option').remove();
$.each(data,function(key, value) {
$select.append('<option value=' + key + '>' + value + '</option>');
});
}
});
Ordering within your SQL statement would be the best solution here:
ORDER BY storeid, client_loc, city, state
and then loop over your query and generate the options.
But to answer your question:
If you want to sort an unlinked struct (dStruct) and keep an ordered struct, you have to use a linked struct (LinkedHashMap):
<cfset sortedKeys = structSort(dStruct, "textnocase", "asc")>
<cfset sortedStruct = createObject("java", "java.util.LinkedHashMap").init()>
<cfloop array="#sortedKeys#" index="key">
<cfset sortedStruct[key] = dStruct[key]>
</cfloop>
<cfoutput>
<select>
<cfloop collection="#sortedStruct#" item="key">
<option>#encodeForHtml(sortedStruct[key])#</option>
</cfloop>
</select>
</cfoutput>
Note that using cfdump does not display the real order of a linked struct.
thanks so much for your help. I figured out a solution... by returning an array of objects.
function getstoresbyretailer(retailer_id) {
$.ajax({
url: "/functions.cfc",
cache: false,
type: "get",
dataType: "json",
data: {method: "getstoresbyretailer", retailer_id: (retailer_id)},
success: function (data) {
var $select = $('#storeid');
$select.find('option').remove();
$.each(data, function(key, value) {
$select.append('<option value=' + value.storeid + '>' + value.store + '</option>');
});
}
});
}
And the ColdFusion Function...
<cffunction name="getstoresbyretailer" access="remote" returnformat="json" output="no">
<cfargument name="retailer_id" type="numeric" required="yes">
<cfset var dArray = []>
<cfif arguments.retailer_id neq 0>
<cfquery name="gds" datasource="#application.dsn#">
SELECT * FROM stores WHERE region_id = #arguments.retailer_id#
ORDER BY client_loc ASC
</cfquery>
<cfif gds.recordcount>
<cfoutput query="gds">
<cfset dStru = { "storeid" = "#gds.storeid#", "store" = "#gds.client_loc# - #gds.city#, #gds.state#" }>
<cfset ArrayAppend( dArray, dStru )>
</cfoutput>
</cfif>
</cfif>
<cfreturn SerializeJSON(dArray) />
</cffunction>
Figured someone might be able to use this one day.

Form submitting using Ajax?

My form submits and it shouldn't as I am using aJax?! If I remove the form tag and closing form tag then it works but doesn't upload the image
$('#savebutton').click(function() {
preventDefault();
var val1 = $('#rsPubName').val();
var val2 = $('#address').val();
var val3 = $('#rsLat').val();
var val4 = $('#rsLong').val();
var val5 = $('#add2').val();
var val6 = $('#rsTown').val();
var val7 = $('#rsCounty').val();
var val8 = $('#rsPostCode').val();
var val9 = $('#region').val();
var val10 = $('#PremisesType').val();
var val11 = $('#rsTel').val();
var val12 = $('#rsWebsite').val();
var val13 = $('#rsAboutpub').val();
var val14 = $('#img1').val();
var val15 = $('#offer1').val();
$.ajax({
type: 'POST',
url: 'addpub-script.php',
enctype: 'multipart/form-data',
data: { rsPubName: val1, address: val2, rsLat: val3, rsLong: val4, add2: val5, rsTown: val6, rsCounty: val7, rsPostCode: val8, region: val9, PremisesType: val10, rsTel: val11, rsWebsite: val12, rsAboutpub: val13, img1: val14, offer1: val15},
success: function(response) {
$('#result').html( '<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>New venue added!</strong> Why not add another?</div>').fadeIn()
}
});
});
preventDefault(); is a method on the event object. It should be:
$('#savebutton').click(function(event) {
event.preventDefault();
...
});
where event is a passed in parameter prefilled by jQuery. See this page and the fourth method down.

Updating local ColdFusion variable in Ajax

I have been trying to perform a simple task (in ASP) for a coldfusion page. I have a local variable "pt.PreCaution" that I need updated. I have tried the following code with no success.
<cfset pt.PreCaution = "">
<label>
Patient Precaution:
</label>
<br>
<cfselect name="lstPreCaution" multiple="yes"
query="GetPreCaution"
value="IsoTypeID"
display="IsoTypeName"
size="8"
required="yes"
width="100"
height="25"
label="Precaution: "
onclick="PreCautionSelected(this)"
>
</cfselect>
function PreCautionSelected(val){
var result ="";
var frm=eval('document.next');
for(i = 0 ; i < val.children.length; i++)
{
if(val.children[i].selected){
if(result.length < 1)
{
result = val.children[i].value;
}
else
{
result = result + "," + val.children[i].value;
}
}
}
$.ajax({
type: "POST",
url: "details.cfm",
data: { "#pt.PreCaution#" : result}
}).done(function(){alert(result)})
}
I modified the ajax call as follows:
function PreCautionSelected(val){
var result ="";
var frm=eval('document.next');
for(i = 0 ; i < val.children.length; i++)
{
if(val.children[i].selected){
if(result.length < 1)
{
result = val.children[i].value;
}
else
{
result = result + "," + val.children[i].value;
}
}
}
$.ajax({
type: "POST",
url: "FileUpdater.cfc?method=setPrecautionType",
data: { lstPrecaution : result}
}).done(function(){})
}
<cfcomponent>
<cffunction name="setPrecautionType" access="remote" returntype="Any" >
<cfargument name="lstPrecaution" type="any" required="true" >
<cfset session.lstPreCaution = #arguments.lstPrecaution#>
<cfreturn />
</cffunction>
</cfcomponent>
I added the following CFC file. This file updates the session variables.
CFC File
Thanks for the input. The Ajax function is getting called and the complete data is being extracted. The only problem is the ColdFusion variable is not getting updated on the server side.
I fixed this problem by written the data to the session data. The problem is the old CF5 frame work that the program is written in.
You have only one mistake.select box not have onclick functionality so you have onchange function means working fine

dropdown populated on basis of another using ajax in coldfusion, not working

I have searched a lot through this website and found some similar posts, but they could not help. I have 2 dropdowns. The first is populated through an inline query. The second needs to be populated through the first's selection. I know cfselect and cfajaxproxy are 2 of the simplest things, but I want to use them on Railo which doesn't support them (checked and returned disappointed).
The ajax code goes like this:
$.ajax({
type: 'POST',
url: 'admin/getModelsForManufs.cfc?method=getModels&returnFormat=JSON',
data: {manuid:selected},
dataType: "text",
success: function(res) {
var newoptions = "";
for(var i=0; i<res.length; i++) {
newoptions += "<option value=\"" + res[i].ID + "\">" + res[i].NAME + "</option>";
}
$("#model").append(newoptions);
},
error: function(x) {
alert(x.responseText);
}
});
Where manuid is the first selection, and model is the html field ID for second dropdown to be populated. The cfc has the following:
<cffunction name="getModels" access="remote" returnType="array">
<cfargument name="manuid" type="numeric" required="true" default="#url.manuid#">
<cfset var data="">
<cfset var result=[]>
<cfset var i=0>
<cfquery name="data" datasource="#THIS.dsn#">
select modelId, modelName
from tablename
where manufacturerid = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.manuid#">
</cfquery>
<cfloop index="i" from="1" to="#data.RecordCount#">
<cfset model = {}>
<cfset model.NAME = data.modelName[i]>
<cfset model.ID = data.modelId[i]>
<cfset arrayAppend(result, model)>
</cfloop>
<cfreturn result>
</cffunction>
In Firebug, the data is in the format:
[{"ID":84.0,"NAME":"name 1"},{"ID":1.0,"NAME":"name 2"}]
which looks correct and there are many more records returned. Have tried most of the tricks but still scratching my head as to why the second dropdown doesn't populate. Any help is highly appreciated. Thanks in advance.
Try this code
$.ajax({
type: 'POST',
url: 'admin/getModelsForManufs.cfc?method=getModels&returnFormat=JSON',
data: {manuid:selected},
dataType: "text",
success: function(res) {
var res2 = JSON.parse(res);
var newoptions = "";
for(var i=0; i<res2.length; i++) {
newoptions += "<option value=\"" + res2[i].ID + "\">" + res2[i].NAME + "</option>";
}
$("#model").append(newoptions);
},
error: function(x) {
alert(x.responseText);
}
});

Resources