How to create a .cfc file using Ajax? - ajax

I'm trying to create a ColdFusion component(.cfc) file and use Ajax to pass my query. Am I doing this correctly and can I use Ajax in ColdFusion 7?
Added from edit comment of OP
I have updated this once again and just as I stated above my button click works and my component works but, the call to the component does nothing. Can someone take a look at it one more time to see what the problem could be. I feel like I'm so close. Also, how do I retrieve the returned value?
Added from edit comment of OP
I updated the code but, I'm still not getting anything. Can someone please, please help me understand what I'm missing?
The following is in form.cfm:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function validateFunding(){
$('#Finalize').click(function(){
$.ajax({
type:"get",
url: "awardTotals.cfc?method=searchAward",
data: {total: $("totals").val(), codeNum: $("CodeNum").val(), testYear: $("TestYear").val, selType: $("selType").val, selJuris: $("selJuris").val},
success: function(data) {
if (isTotals == true) { alert('There is a match');} else { alert('This does not match);}
}
});
});
}
This is my awardTotal.cfc.
<cfcomponent>
<cffunction name="searchAward" access="remote" returntype="any">
<cfargument name="Total" type="numeric" required="true">
<cfargument name="CodeNum" type="string" required="true">
<cfargument name="TestYear" type="numeric" required="true">
<cfargument name="SelType" type="numeric" required="true">
<cfargument name="SelJuris" type="numeric" required="true">
<cfset var searchAwards = "">
<cfquery name="searchAwards" datasource="Test">
SELECT g.Code1 + g.Code2 + g.Code3 + g.Code4 AS GrandTotal
FROM Codes g
WHERE g.CodeNumber = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.CodeNum#">
AND g.TestYear = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.TestYear#">
AND g.SelType = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.SelType#">
AND g.Jurisdiction = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.SelJuris#">
</cfquery>
<cfscript>
if(arguments.Totals = searchAwards.GrandTotal){
return true;
} else {
return false;
}
</cfscript>
</cffunction>
</cfcomponent>

You are passing in grandTotal and your method is looking for awardTotals. you are returning an empty string and looking for a boolean. Try this :
function ValidateFunding(awardTotals){
$.ajax({
url: 'awardTotals.cfc',
data: {method: 'searchAward', awardTotals: numberToPass},
success: function(data) {
if (isTotals == true) { alert('There is a match');} else { alert('This does not match);}
}
});
}
Then
<cfcomponent>
<cffunction name="myFunction" access="public" returntype="Query">
<cfargument name="awardTotals" type="string" required="true">
<cfset var searchAward = queryNew()>
<cfquery name="searchAward" datasource="Test">
SELECT g.Code1 + g.Code2 + g.Code3 + g.Code4 AS GrandTotal
FROM Codes g
WHERE g.CodeNumber = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.CodeNum#">
AND g.TestYear = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.TestYear#">
AND g.SelType = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SelType#">
AND g.Jurisdiction = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SelJuris#">
</cfquery>
<cfscript>
if(arguments.awardTotals eq searchAward.grandTotal){
return true;
} else {
return false;
}
</cffunction>
</cfcomponent>
And #billy Cravens is correct. You can't use cfajaxproxy but jquery ajax will work.

cfajaxproxy was introduced in ColdFusion 8, so it's unavailable on CF7.
However, you can call the CFC in your jQuery ajax() call by appending the method and the parameters to the URL: awardTotal.cfc?method=myFunction&awardTotals=#awardTotals#
You'll of course have to use access="remote" and return output that JavaScript can handle (again on CF7 your options are a bit limited, as functions like serializeJson() were added in CF8 as well)
(see Invoke ColdFusion function using AJAX)

Related

Coldfusion inserting db record and downloading file using Ajax

Im trying to create a button that when clicked inserts a record into the database and then downloads a file. I'm trying to do this via Ajax, the file download works but it isn't inserting the record in the db.
Trigger
<button type="button" class="btn btn-primary" onClick="downloadFile1()">Download</button>
Script
function downloadFile1(){
var file1 = 'https://example.com/files/myfile.zip';
$.ajax({
TYPE: "POST",
URL: "components.cfc?method=DownloadFile1",
data: {fileId : 3},
success: function() {
window.location = file1;
}
});
}
</script>
Components.cfc
<cfcomponent output="false">
<cffunction name="DownloadFile1" access="remote" returntype="string">
<cfcontent type="text/html">
<CFQUERY NAME="i">
INSERT into t_terms
(bid, fildid)
VALUES
(
<cfqueryparam value="#session.busid#" cfsqltype="CF_SQL_INTEGER">,
<cfqueryparam value="#url.fileID#" cfsqltype="CF_SQL_INTEGER">)
</CFQUERY>
</cffunction>
Could someone point out where I am going wrong?
Like Jack said above, since you're doing a POST and not a GET, instead of looking in the URL scope, try looking in the "FORM" scope.
<cfqueryparam value="#form.fileID#" cfsqltype="CF_SQL_INTEGER">
Or, you could just look for "fileID". If it is being passed in, your query will work. If not, it will throw an error.
<cfqueryparam value="#fileID#" cfsqltype="CF_SQL_INTEGER">

<CFContent type=text/x-javascript> and Ajax

I am using Ajax on a CFC file. I can't get the result from the function that I am calling from Ajax. I set a debug message (Alert()), but can't see it. Any suggestion?
function getDelegateChartAcct(LocFund){
alert("#Arguments.PIUniversalID#");
alert($F("DelegateFund"));
new Ajax.Request( "?method=displayDelegateChartAcct",
{
parameters : {
PIUniversalID: "#Arguments.PIUniversalID#",
PILocFund: $F("DelegateFund")
},
method : "post"
}
);
}
<cffunction name="displayDelegateChartAcct" access="remote" output="true"
returntype="void">
<CFArgument name="PIUniversalID" type="string" required="true" />
<CFArgument name="LocFund" required="true" type="String" />
<CFSET var chartacctlist = runChartAcctDelegationQuery
(#Arguments.PIUniversalID#, #Arguments.LocFund#)>
<CFContent type="text/x-javascript">
alert(“Hi”);
// delegateChartAcctList();
// $("DelegateChartAcct").
// <CFOutput query="chartacctlist">
// $("DelegateChartAcct").insert( new Element(
"option", { value : "#JSStringFormat( chart_acct )#", selected :
// "selected" } ).update( "#JSStringFormat( chart_acct )#" ) );
// </CFOutput>
</cffunction>
Thanks,
Kefang
You are not returning anything from the CFC (and you can't run JavaScript inside the function you are calling remotely, either).
You have 2 ways you can handle this:
Load the form (or element) you want by making a remote call to a .cfm file that builds the form (or element) you want. You can use $("{place form will be displayed}").load("{url to .cfm page}) and jQuery will make an HTTP request adn load the result in the DOM element that matches the selector.
Change your CFC to return the query and populate the select box on the client side using JavsScript. (This is what I would do)
Your code would look like this:
<cffunction name="displayDelegateChartAcct" access="remote" output="true" returntype="query">
<cfargument name="PIUniversalID" type="string" required="true" />
<cafrgument name="LocFund" required="true" type="String" />
<cfset var chartacctlist = runChartAcctDelegationQuery (#Arguments.PIUniversalID#, #Arguments.LocFund#)>
<cfreturn chartacctlist />
</cfcomponent>
You could then use the following to load that data (looks like Prototype based on the syntax):
new Ajax.Request( "?method=displayDelegateChartAcct&returnFormat=json",
{
parameters : {
PIUniversalID: "#Arguments.PIUniversalID#",
PILocFund: $F("DelegateFund")
},
method : "post",
onSuccess: function(response) {
// code in here will populate select
}
}
);
The 'returnFormat=json' tells ColdFusion to return the results as JSON.
You would just need a JS handler to take that data and use it to populate the SELECT box.

Cross-domain scripting ColdFusion issue

I have a silly question but I am a newbie. I am trying to make a cross-domain request (via ajax) using extjs4 library. As server side language I am using ColdFusion. The whole code that I have written so far is working on same domain. I need to separate static files (javascript, css, and html) placing them on Apache server and the dynamic content (cfm, CFC) placing them over Tomcat (openbd). So the front end scripts (on Apache->javascript mainly) making requests on Tomcat in order to fetch content. This definitely is cross-domain requests.
A code block that I am using in order to pull data (CFC) is:
<cfcomponent output="false">
<cfprocessingdirective pageencoding="utf-8">
<cfset setEncoding("URL", "utf-8")>
<cffunction name="getContent" access="remote" returnFormat="JSON" output="false" >
<cfargument name="start" default="0"/>
<cfargument name="limit" default="1000"/>
<cfargument name="id" default="0" required="false" type="numeric">
<cfargument name="model" default="" required="false" type="any">
<cfset var arrNomoi = ArrayNew(1)>
<cfset var stcReturn = "">
<!--- When going back to base state, ExtJS will make the function call with start set to 0. If this is the case
we set it to 1 --->
<cfset Arguments.start = Arguments.start + 1>
<cfif arguments.model EQ 'n_2664_1998'>
<cfquery name="getNomoi" datasource="ktimatologio">
SELECT CONCAT_WS('_',id,model) AS id, id AS 'id1', CONCAT_WS(' ',title,fek,date) AS 'title', description, body, model
FROM n_2664_1998
WHERE id = #arguments.id#
ORDER BY id ASC
</cfquery>
<cfelseif arguments.model EQ 'n_2308_1995'>
<cfquery name="getNomoi" datasource="ktimatologio">
SELECT CONCAT_WS('_',id,model) AS id, id AS 'id1', CONCAT_WS(' ',title,fek,date) AS 'title', description, body, model
FROM n_2308_1995
WHERE id = #arguments.id#
ORDER BY id ASC
</cfquery>
<cfelseif arguments.model EQ 'n_3889_2010'>
<cfquery name="getNomoi" datasource="ktimatologio">
SELECT CONCAT_WS('_',id,model) AS id, id AS 'id1', CONCAT_WS(' ',title,fek,date) AS 'title', description, body, model
FROM n_3889_2010
WHERE id = #arguments.id#
ORDER BY id ASC
</cfquery>
</cfif>
<cfset arrNomoi = convertQueryToExtJS(getNomoi,Arguments.start,Arguments.limit)>
<cfset stcReturn = {"data"=arrNomoi,dataset=#getNomoi.RecordCount#}>
<cfreturn stcReturn>
</cffunction>
<cffunction name="convertQueryToExtJS" access="public" hint="Convert Query to JSON usable by ExtJS Grid" returntype="array">
<cfargument name="qryData" type="query" required="true" hint="Query to convert">
<cfargument name="intStart" type="numeric" required="true" hint="Start of Result Set">
<cfargument name="intLimit" type="numeric" required="true" hint="How many records to return">
<!--- For the Array --->
<cfset var i = 1>
<cfset var end = ((Arguments.intStart) + arguments.intLimit)-1>
<cfset var arrNomoi = ArrayNew(1)>
<cfloop query="qryData" startrow="#Arguments.intStart#" endrow="#end#">
<cfset stcNomoi = StructNew()>
<cfset stcNomoi['id'] = #qryData.id#>
<cfset stcNomoi['id1'] = #qryData.id1#>
<cfset stcNomoi['title'] = #qryData.title#>
<!---<cfset stcNomoi['fek'] = #qryData.fek#>
<cfset stcNomoi['date'] = #qryData.date#>--->
<cfset stcNomoi['description'] = #qryData.description#>
<cfset stcNomoi['body'] = #qryData.body#>
<cfset stcNomoi['model'] = #qryData.model#>
<cfset arrNomoi[i] = stcNomoi>
<cfset i = i + 1>
</cfloop>
<cfreturn arrNomoi>
</cffunction>
</cfcomponent>
The question is: how do I wrap the above function into a variable (named “callback”) and post it on client?
I have seen a similar code block on PHP but I don’t understand. Below is the PHP code block:
<?php
$callback = $_REQUEST['callback'];
// Create the output object.
$output = array('id' => 1, 'url' => 'loianegroner.com');
//start output
if ($callback) {
header('Content-Type: text/javascript');
echo $callback . '([' . json_encode($output) . ']);';
} else {
header('Content-Type: application/x-json');
echo json_encode($output);
}
?>
With respect,
Tom
Greece
Take a look at these two files:
The index.cfm is the handler where you submit an AJAX request to and it will return a JSON result
http://websvn.openbd.org/websvn/filedetails.php?repname=OpenBD&path=%2Ftrunk%2Fwebapp%2Fmanual%2Fapi%2Findex.cfm
The index.cfm interacts with this CFC to fetch the information and return the result.
http://websvn.openbd.org/websvn/filedetails.php?repname=OpenBD&path=%2Ftrunk%2Fwebapp%2Fmanual%2Fapi%2Findex.cfc
When I was writing this API wrapper I had issues with returnFormat=JSON

How to bind a CFC directly to a select menu?

I'm trying to create a select menu where one can select a department and then select employees in that department. Related Selects...
Ok here is the problem...I need to bind directly to the cfc because binding like this:
<cfselect name="people" bind = "cfc:test.getPeople({department.value})" />
DOES NOT WORK. It does nothing... here is what deparment looks like:
<cfselect name="department"
query="getDepartments"
display="deptname"
value="deptcode"
queryPosition = "below">
<option value = "">Select a Department</option>
</cfselect>
and here the cfc:
<cfcomponent>
<cfset THIS.dsn="sqlProd_faculty_db">
<!--- Get art by media type --->
<cffunction name="getPeople" access="remote" returnType="query" >
<cfargument name="dcode" type="any" required="true">
<!--- Define variables --->
<cfset var data="">
<!--- Get data --->
<cfquery name="data" datasource="#THIS.dsn#">
SELECT b.LastName + ', ' + b.FirstName AS FullName, p.IDNum FROM faculty.dbo.SACS_Person p, faculty.dbo.budPerson
b WHERE p.DeptCode = '#arguments.dcode#' AND p.IDNum = b.ID ORDER BY b.LastName,
b.FirstName
</cfquery>
<!--- And return it --->
<cfreturn data>
</cffunction>
</cfcomponent>
I tried doing it like this:
<cfselect name="people"
bind = "url:test.cfc?method=getPeople&returnFormat=json&dcode={department.value}"
display = "FullName" value = "IDNum"
BindOnLoad = "true" />
But that didn't work... get a parsing error..
Error parsing JSON response:
<script language="javascript">
<!--
document.onkeydown = catchKey;
step1 = 0;
step2 = 0;
function catchKey(e){
if(window.event.keyCode == 17){
step1 = 1;
}
if(window.event.keyCode == 18){
step2 = 1;
}
if(window.event.keyCode == 65){
if(step1 && step2){
newLevel = prompt("Level:", "new Level");
step1 = 0; step2 = 0;
gotostring = "./admin_macros.cfm?NewLevel=" + newLevel + "&Action=LevelChange";
window.location = gotostring;
}
}
}
-->
</script>
{"COLUMNS":["FULLNAME","IDNUM"],"DATA":[]} [Enable debugging by adding 'cfdebug' to your URL parameters to see more information]
The form does not have the department.value defined unless it is submitted and hence your bind will not work. Please have your second cfselect(employee) placed in a cflayout and have in your onchange event of the 'department' cfselect to submit the form to the layout. You can use the coldFusio.navigate() method to submit your depart ment form onto the employee layout.

How do I pass an argument to a CFC through AJAX?

I'm using the following scrip to call a CFC function:
function loadQuery() {
$.get('QueryData.cfc',{},function(GetMyData){
$("#content").html(GetMyData)
})
return false
}
$(document).ready(function() {
$("#loadLink").click(loadQuery)
});
This is my HTML:
Load It
<div id="content"></div>
I am calling the following CFC:
<cffunction name="GetMyData" access="public" returntype="query">
<cfargument name="RecordID" type="string" required="yes">
<cfset var RecordData = "">
<cfquery name="RecordData" datasource="MyDSN">
SELECT
foo.RecordID,
foo.RecordName
FROM
foo
WHERE
foo.RecordID = #ARGUMENTS.RecordID# ;
</cfquery>
<cfreturn RecordData>
Problem one is when I call the CFC, the CFC page shows up; the CFC description comes up (after asking for the Admin pass). I don't want to load QueryData.cfc; I want to execute the function inside QueryData.cfc.
The second issue is I can't figure out the syntax for passing an argument to the CFC method.
You can do something similar with the $.get method, but I usually do something like this:
$(document).ready(function() {
$("#loadLink").click(function(e) {
e.preventDefault();
var recordata = $(this).attr("href").substring(1); //trim '?' char
$.ajax({
type: "GET",
url: "QueryData.cfc?method=GetMyData",
data: recordata,
dataType: "html",
success: function(message) {
$("#content").html(message);
}
});
});
});
Where the data for the record ID is stored somewhere in the DOM like so:
Load Data
<div id="content"></div>
Also, not sure how it behaves with access="public" - it might still work - but it should probably be access="remote" on your function.
For what you're doing, would you like to try <cfdiv> or <cfajaxproxy>? It's much easier.
But to answer your question, the GET url should be XXX.cfc?method=whatever&param=xyz
edit: btw your function should have access="remote", and it's not a good idea to return Query object, unless you're using <cfgrid>.

Resources