I am trying to set up a system that allows me to get data from my ColdFusion database from my JavaScript code. However, I am running into an error and I am not sure what is causing it. I am new to CF and the engine I am running is ColdFusion MX 7.
Here is the CFC file, cfquery.cfc
:
<cfcomponent output="no">
<cffunction name="phonebookQuery" access="remote" returnType="struct">
<cfargument name="select" type="string" required="yes">
<cfargument name="from" type="string" required="yes">
<cfargument name="where" type="string" required="yes">
<cfargument name="orderBy" type="string" required="yes">
<cfquery name="query" datasource="phonebook">
SELECT #select#
FROM #from#
WHERE #where#
ORDER BY #orderBy#
</cfquery>
<cfreturn query>
</cffunction>
</cfcomponent>
I am probably not returning things correctly, but my code doesn't get that far in execution for me to find out.
This is the JS function that performs the AJAX call. I know I shouldn't use async: false
, but I just need something that works for now. I plan on implementing either promises or callbacks once I get it working.
function cfQuery(p){
var result;
var queryStr= "cfquery.cfc?method=phonebookQuery&" +
"select="+p.select+"&"+
"from="+p.from+"&"+
"where="+p.where.replace("=","%3D")+"&"+
"orderBy="+p.orderBy;
$.get( queryStr, function(data){
result=data;
});
return result;
}
The specific example of the function call I am trying to get to work is:
var query_result= cfQuery({
select: "*",
from: "shareloantypes",
where: "share_loan='S'",
orderBy: "share_loan_type"
});
I get an internal server error when I try to run the code. it complains about the syntax near the where clause in the SQL:
Error Executing Database Query.
[Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC SQL Server Driver][SQL Server]
Line 1: Incorrect syntax near 'S'.
The error occurred in C:\Inetpub\wwwroot\xxxxxx\report\cfquery.cfc: line 12
10 : FROM #from#
11 : WHERE #where#
12 : ORDER BY #orderBy#
13 : </cfquery>
14 : <cfreturn query>
SQL SELECT * FROM shareloantypes WHERE share_loan=''S'' ORDER BY share_loan_type
DATASOURCE phonebook
VENDORERRORCODE 170
SQLSTATE 42000
You can see that my 'S' is being replaced with ''S''. How can I fix this?, If I replace where: "share_loan='S'"
with where: "share_loan=S"
in the function call then the SQL that gets generated has no quotes at all, rather than 2 on each side and I get "invalid column name".