How to bind a CFC directly to a select menu? - ajax

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.

Related

If user logoff or their session times out how to end coldfusion session?

I have system that I built and for this project I used Ajax with JQuery. On back end I use ColdFusion and session management to handle users session variables. There is two situations (actually three if we consider closing the browser) where users session will end. One situation is if they click Logout then I have function that will clear SESSION scope with all information in it but session is not ended. Also CFID and CFTOKEN are still the same. Here is example of Logout function:
<cffunction name="LogOut" access="remote" output="yes" returnformat="JSON" hint="Used in session timeout handling">
<cfset fnResults = structNew()>
<cfset dt = createODBCDateTime(now())>
<cfif structKeyExists(SESSION,"LoggedIn")>
<cfset temp = structClear(SESSION)>
<cfset fnResults.status = "200">
<cfelse>
<cfset fnResults.status = "400">
<cfset fnResults.message = "Error!">
</cfif>
<cfreturn fnResults>
</cffunction>
Second scenario is once user session timeout. Here is example of that fucntion:
<cffunction name="timeoutSession" access="remote" output="yes" verifyclient="no" securejson="false">
<cfset temp = structClear(SESSION)>
</cffunction>
Both of these functions will clear the session scope but not end the user session. I have used cfdump to check session scope once user logs out and CFID/CFTOKEN remains the same. I'm wondering how session cna be ended once they hit LogOut or timeoutSession function? Also should I rewrite the CFID and CFTOKEN every time user logs in the system? Here is example of my Application.cfc:
<cfcomponent output="false">
<cfset THIS.name = "MyApplication">
<cfset THIS.sessionManagement = true>
<cfset THIS.applicationTimeout = CreateTimeSpan(0, 8, 0, 0)>
<cfset THIS.sessionTimeout = CreateTimeSpan(0, 2, 0, 0)>
<cfset THIS.requestTimeOut = "60">
<cffunction name="onApplicationStart" access="public" returntype="boolean" output="false">
<cfset APPLICATION.appStarted = now()>
<cfset APPLICATION.title = "My Application">
<cfset APPLICATION.functions = CreateObject("component","udfs").init()>
<cfset APPLICATION.sessionMinutes = 30>
<cfreturn true>
</cffunction>
<!--- Runs when your session starts --->
<cffunction name="OnSessionStart" access="public" returntype="void" output="false">
<!--- Clear the session. --->
<cfset StructClear( SESSION ) />
<!--- Set loggedin flag to false. --->
<cfset SESSION.loggedin = false>
<cfreturn />
</cffunction>
<!--- Run before the request is processed. --->
<cffunction name="onRequestStart" returnType="boolean" output="false">
<cfargument name="thePage" type="string" required="true">
<cfset REQUEST.appCode = 'SPA'>
<cfset REQUEST.appName = 'Single Page Application'>
<cfset var page = listLast(arguments.thePage,"/")>
<!---<cfset onApplicationStart()>--->
<cfif !listFindNoCase("Login.cfm,Authentication.cfc",page)>
<cfif !structKeyExists(SESSION, "loggedin") OR SESSION.loggedin EQ false>
<cflocation url="Login.cfm" addToken="false">
</cfif>
</cfif>
<cfreturn true>
</cffunction>
</cfcomponent>
I'm not sure if session can be ended in Application.cfc or I have to do that in my cffunctions. Same for CFID and CFTOKEN what is the best place to set new values if user logs in again? If aynone have experience with this please let me know. I'm trying to prevent user to use the same session and raise level of security in my SPA.

dhtmlxGrid : Cliclking header in Big Data grid

I'd like to maintain page location while click onto header.
But if I'm in page 5 and click onto header then page location changed to 1 page.
(sort is perfect)
I want maintain my page location if I click onto header in page 5, still maintain location
5 page and sorting is perfectly.
I think this is not enough to explain my situation. So I post my development environment
I'm using struts2 and mysql. and here's my javascript.
function fnGridInitSW(){
swgrid = new dhtmlXGridObject('swGridBox');
swgrid.setImagePath("../../../common/img/dhtmlx/grid/");
swgrid.setHeader("SoftWareName, company, version, Install_date");
swgrid.setColumnIds(
"COL_1"
+",COL_2"
+",COL_3"
+",COL_4"
);
swgrid.setInitWidthsP("25,25,25,*");
swgrid.setColTypes("ro,ro,ro,ro");
swgrid.setColSorting("str,str,str,str");
swgrid.attachEvent("onXLS", function(){
$("#swnotfound").hide();
$("#swgridLoading").show();
});
swgrid.attachEvent("onXLE", function(){
$("#swgridLoading").hide();
swgrid.changePage(chPg);
$("#swnotfound").hide();
});
swgrid.init();
swgrid.attachEvent("onBeforePageChanged",function(ind,count){
chPg = count;
if (!swgrid.getRowsNum()){
return false;
};
return true;
});
var mygrid_state = swgrid.getSortingState();
popFnSearch(swgrid.getColumnId(mygrid_state[0]), mygrid_state[1]);
// Custom Sorting
swgrid.attachEvent("onBeforeSorting",function(ind, type, direction) {
popFnSearch(swgrid.getColumnId(ind), direction);
var sInd;
var mygrid_state = swgrid.getSortingState();
if( typeof(mygrid_state[0]) == "undefined" ){
sInd = ind;
}
direction = (mygrid_state[1] == "des") ? "asc": "des";
swgrid.setSortImgState(true,sInd,direction);
return true;
});
}
function popFnSearch(sortC, sortD) {
if( typeof(sortC) == "undefined" ) sortC = swgrid.getColumnId(3);
if( typeof(sortD) == "undefined" ) sortD = "desc";
var params = "/url/Info.do?"&sortC="+sortC+"&sortD="+sortD+"&pageCnt=5";
swgrid.clearAndLoad(params);
}
here's my xml for grid.
<%# page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<rows total_count='<s:property value="%{totalCnt}" />' pos='<s:property value="%{posStart}" />'>
<s:if test="softwareList.size > 0">
<s:iterator value="%{softwareList}" status="index">
<row id="'index<s:property value='%{SW_SEQNO}'/>'">
<cell><s:property value="%{SW_NM}" /></cell>
<cell><s:property value="%{SW_COMPANY}" /></cell>
<cell><s:property value="%{SW_VER}" /></cell>
<cell class="last"><s:property value="%{INST_DT}" /></cell>
</row>
</s:iterator>
</s:if>
</rows>
here's my query
//get total count from softwarelist
<select id="getSoftwareInfoTotCnt" resultClass="Integer" parameterClass = "d">
SELECT IFNULL(COUNT(*), 0)
FROM T_PC_SW_LIST sl
JOIN T_SOFTWARE so ON sl.SW_SEQNO = so.SW_SEQNO
</select>
//get real data from softwarelist
<select id="getSoftwareInfo" resultClass="c" parameterClass = "d">
SELECT
sl.SW_SEQNO
, sl.ASST_SEQNO
, so.SW_NM
, so.SW_COMPANY
, so.SW_VER
, DATE_FORMAT(sl.INST_DT, '%Y-%m-%d') AS INST_DT
FROM T_PC_SW_LIST sl
JOIN T_SOFTWARE so ON sl.SW_SEQNO = so.SW_SEQNO
ORDER BY $sortC$ $sortD$
LIMIT #posStart# , #count#
</select>
If anyone have solution please help me..
You may get the current active page before the sorting started using the getStateOfView() method:
http://docs.dhtmlx.com/doku.php?id=dhtmlxgrid:api_method_dhtmlxgridobject_getstateofview
and then open the needed page after the new sorted data is loaded using the changePage() method:
http://docs.dhtmlx.com/doku.php?id=dhtmlxgrid:api_method_dhtmlxgridobject_changepage

How to create a .cfc file using 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)

<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

Resources