roger v
asked on
Making an ajax call with jQuery in Coldfusion 9
Hi Experts,
I'm trying to implement ajax through jquery but I have never done this before. Currently I have a coldfusion 9 form where I use cfajaxproxy to create a js class of a cfc object. I then create an instance of that js class and using regular javascript I do the function call and set the callback handler and error functions. This is quite cumbersome so I'd like to do this using jquery. How do I modify the following existing code to leverage jQuery? (my js code is attached)
I'm trying to implement ajax through jquery but I have never done this before. Currently I have a coldfusion 9 form where I use cfajaxproxy to create a js class of a cfc object. I then create an instance of that js class and using regular javascript I do the function call and set the callback handler and error functions. This is quite cumbersome so I'd like to do this using jquery. How do I modify the following existing code to leverage jQuery? (my js code is attached)
var updateAppName = function(te){
var objAppInfo = new appinfo();//instance of the js class of the cfc object
var tv = document.getElementById('myInput').value;
objAppInfo.setCallbackHandler(updateInfo);//callback function
objAppInfo.setErrorHandler(myErrorHandler2);//error handler
objAppInfo.funcUpdateAppAcron(tv,te);//the actual call to the remote method that is residing in my cfc
}
var updateInfo = function(res){
if(res==1){
//location.reload(true);
//alert('capturing json data structure..');
return true;
}
else{alert('Error Occurred in updating Name!');}
return false;
}
var myErrorHandler2 = function(statusCode, statusMsg){
alert('Status: ' + statusCode + ', ' + statusMsg);
return false;
}
<!---the file which calls the above function--->
<input type="text" name"myInput" id="myInput" />
<input type="button" name="myBtn" id="myBtn" onclick="javascript:updateAppName(#url.processid#);" />
ASKER
@leakim971:
OK, I changed from regular js to the $.getJSON format. The action takes place and the update works asynchronously but the updateInfo call does not work. I have an alert box in the updateInfo callback handler that displays an alert box based on the returned json data. I opened up fiddler to see the behind-the-scenes json but there is nothing showing up. I don't see any asynchronous call being made.
What am I missing?
OK, I changed from regular js to the $.getJSON format. The action takes place and the update works asynchronously but the updateInfo call does not work. I have an alert box in the updateInfo callback handler that displays an alert box based on the returned json data. I opened up fiddler to see the behind-the-scenes json but there is nothing showing up. I don't see any asynchronous call being made.
What am I missing?
do you have a link to see your page?
ASKER
No, it's only available within our company intranet.
Update: OK for some reason, fiddler wasn't displaying the transaction but now it does. And I see that the transaction is working. But, the callback function has an alert box that is displayed if the returned value is 1. That alert box is not being activated. I did not do a $.ajaxSetup, but instead put the name of the callback function (updateInfo) as a parameter of the jquery ajax call. Could that be the reason?
Update: OK for some reason, fiddler wasn't displaying the transaction but now it does. And I see that the transaction is working. But, the callback function has an alert box that is displayed if the returned value is 1. That alert box is not being activated. I did not do a $.ajaxSetup, but instead put the name of the callback function (updateInfo) as a parameter of the jquery ajax call. Could that be the reason?
lot of scenario, I'm blind...
the ajaxSetup({"error"
is now the most important part to let we know what happen, I suppose you have an error from the server side
the ajaxSetup({"error"
is now the most important part to let we know what happen, I suppose you have an error from the server side
try to see the error with fiddler
ASKER
Fiddler does not show any error. I did add the ajaxSetup line but it does not pop any error. I was reading through the comments on the link that you provided and one of those says that that code does not work with jquery version 1.5 and up. I'm using 1.5.1.min.js.
This is the current code I have:
This is the current code I have:
$.ajaxSetup({ "error": myErrorHandler2 });
var updateAppAcron = function(te){
$.getJSON("/assets/cfc/myCFC.cfc",{"method":"funcUpdate","racename":newNameVal,"racenameold":oldNameVal,"processid":te,"returnformat":"json"},updateInfo);
}
var updateInfo = function(obj){
if(obj==1){
alert('Successfully updated Race location!');
return true;
}
else{alert('Error Occurred in updating race location!');}
return false;
}
var myErrorHandler2 = function(statusCode, statusMsg){
alert('Status: ' + statusCode + ', ' + statusMsg);
return false;
}
>Fiddler does not show any error
so you see the data?
could you post you entire codes ? cfm and myCFC.cfc?
so you see the data?
could you post you entire codes ? cfm and myCFC.cfc?
ASKER
Attached are all the code pages.
<!---.cfm page where jquery is loaded, and the textbox that has the value to be updated asynchronously--->
<script language="javascript" type="text/javascript" src="../../cf_jquery/jquery-1.5.1.min.js"></script>
<script src="../../scripts/races/raceJson.js" language="javascript"></script>
<input type="text" name="racename" value="#racename#" id="racename" />
<input type="button" name="updName" id="updName" value="Change Race Name" onClick="javascript:updateRaceAcron(#url.processid#);" />
<!---.cfc component--->
<cfcomponent>
<cffunction name="funcUpdateRace" access="remote" returntype="any" returnformat="json">
<cfargument name="myarg1" type="string" required="yes">
<cfargument name="myarg2" type="string" required="yes">
<cfargument name="myarg3" type="numeric" required="yes">
<cfset var strRaceNew = arguments.myarg1>
<cfset var strRaceOld = arguments.myarg2>
<cfset var procid = val(arguments.myarg3)>
<cfset intResult = "1">
<cftry>
<!---a couple of cf update queries--->
<cfcatch type="any">
<cfset intResult = "0">
</cfcatch>
</cftry>
<cfreturn intResult>
</cffunction>
</cfcomponent>
<!---the raceJson.js file--->
$.ajaxSetup({ "error": myErrorHandler2 });
var updateRaceAcron = function(te){
$.getJSON("/cfc/races/UpdRaceInfo.cfc",{"method":"funcUpdateRace","myarg1":newNameVal,"myarg2":oldNameVal,"myarg3":te,"returnformat":"json"},updateInfo);
}
var updateInfo = function(res){
if(res==1){
alert('Successfully updated Race Name!');
return true;
}
else{alert('Error Occurred in updating race!');}
return false;
}
var myErrorHandler2 = function(statusCode, statusMsg){
alert('Status: ' + statusCode + ', ' + statusMsg);
return false;
}
you don't need newNameVal and oldNameVal
line 37 :
$.getJSON("UpdRaceInfo.cfc ",{"method ":"funcUpd ateRace"," myarg1":$( "#racename ").val()," myarg2":"n othing_jus t_for_fun" ,"myarg3": te,"return format":"j son"},upda teInfo);
myarg1 is the value of the field racename
myarg2 is not used
te is the value url.processid
line 37 :
$.getJSON("UpdRaceInfo.cfc
myarg1 is the value of the field racename
myarg2 is not used
te is the value url.processid
ASKER
@leakim971:
Changed that but the issue remains the same: the callback function is not being called.
Maybe this way does not work in version 1.5.1 of jquery? I'm trying to do the ajaxSetup to setup the entire request to see if that helps.
Changed that but the issue remains the same: the callback function is not being called.
Maybe this way does not work in version 1.5.1 of jquery? I'm trying to do the ajaxSetup to setup the entire request to see if that helps.
No no it should work I tested it with your code
ASKER
This is the change I made and I'm now able to get the callback function but getting an error in the callback function. It's most probably related to how I'm reading the json object being returned:
$.ajax({
url:"/cfc/races/UpdRaceInf o.cfc",
//global: false,
type: "POST",
data: {
method: "funcUpdateRaceAcron",
racenew: $("#txt_race").val(),
raceold: $("#h_race").val(),
processid: te
},
//dataType: "json",
success: updateInfo(),
});
var updateInfo = function(res){
alert(res);
}
$.ajax({
url:"/cfc/races/UpdRaceInf
//global: false,
type: "POST",
data: {
method: "funcUpdateRaceAcron",
racenew: $("#txt_race").val(),
raceold: $("#h_race").val(),
processid: te
},
//dataType: "json",
success: updateInfo(),
});
var updateInfo = function(res){
alert(res);
}
replace : success: updateInfo(),
by : success: updateInfo,
>but getting an error in the callback function.
this is a good news, I assume the callback in quest is the success one
you can try to return a static object to start
by : success: updateInfo,
>but getting an error in the callback function.
this is a good news, I assume the callback in quest is the success one
you can try to return a static object to start
ASKER
@leakim:
"I assume the callback in quest is the success one
you can try to return a static object to start"
Yes the callback is being invoked, but what do you mean by 'static object'? Right now, all that the cfc is returning is the number 1.
"I assume the callback in quest is the success one
you can try to return a static object to start"
Yes the callback is being invoked, but what do you mean by 'static object'? Right now, all that the cfc is returning is the number 1.
ASKER
So I'm able to return not just the 1, but also a structure. But the problem I'm having is how do I access this returned data?
This is the data and json format that is now being returned:
{"SUCCESS":true,"ERRORS":" "}
In my callback, I need to check for SUCCESS. If it is true, return true, else return false. What is the syntax for this? Right now I just have following:
alert(res);
I tried alert(res[1]) to access the value of SUCCESS but that doesn't work.
This is the data and json format that is now being returned:
{"SUCCESS":true,"ERRORS":"
In my callback, I need to check for SUCCESS. If it is true, return true, else return false. What is the syntax for this? Right now I just have following:
alert(res);
I tried alert(res[1]) to access the value of SUCCESS but that doesn't work.
Try : alert( res.SUCCESS )
Or : alert( eval( "(" + res + ")" ).SUCCESS )
Or : alert( eval( "(" + res + ")" ).SUCCESS )
ASKER
Nope, neither of them worked. I get a javascript error: object does not support this property
could you paste what you get in the alert with :
alert( JSON.stringify( res ) );
alert( JSON.stringify( res ) );
ASKER
Here's what I'm seeing in fiddler:
{"SUCCESS":true,"ERRORS":" "}
I tried several combination to retrieve the value of SUCCESS and ERRORS including - res.SUCCESS[0], res.SUCCESS, the eval method, but all of them blow up. For some reason, I'm not getting the syntax right.
{"SUCCESS":true,"ERRORS":"
I tried several combination to retrieve the value of SUCCESS and ERRORS including - res.SUCCESS[0], res.SUCCESS, the eval method, but all of them blow up. For some reason, I'm not getting the syntax right.
forget fiddler, please paste what you get in the alert
ASKER
I get a js error:
'JSON' is undefined
'JSON' is undefined
ASKER
OK, in order to use the json object, i've got to load a json2.js file?
incluse your own copy of this javascript in your page : https://raw.github.com/douglascrockford/JSON-js/master/json2.js
<script type="text/javascript" language="javascript" src="update/this/path/to/y our/own/js on2.js"></ script>
<script type="text/javascript" language="javascript" src="update/this/path/to/y
>OK, in order to use the json object, i've got to load a json2.js file?
eh eh, yes, this is the prupose of my previous post
eh eh, yes, this is the prupose of my previous post
ASKER
OK, so I included the json2.js file and used the stringify method and get a whole bunch of json data. I tried using the JSON.parse(res) method but that blew up. Here is the stuff coming back in the alert box using stringify:
"{\"SUCCESS\":true,\"ERROR S\":\"\"}\ r\n</td></ td></td></ th></th></ th> And a bunch of other html tags
So now the challenge is to parse this shinola load of stuff using JSON.parse. How do I do that?
"{\"SUCCESS\":true,\"ERROR
So now the challenge is to parse this shinola load of stuff using JSON.parse. How do I do that?
ASKER
I used the following to loop over the content of the json object but it doesn't work:
var resultObj = JSON.parse(res);
for(var x=0;x<resultObj.length;x++ ){
alert(resultObj[x]);
}
var resultObj = JSON.parse(res);
for(var x=0;x<resultObj.length;x++
alert(resultObj[x]);
}
ok, this is not clean, I just want to be sure we receive a true valid Object.
we've two solutions
- a quick one : res = JSON.parse( res.split(/\r/)[0] );
- the right one is to get rip of all this bunch of html tag : could you confirm you don't send anything else than the content in your cfc code?
we've two solutions
- a quick one : res = JSON.parse( res.split(/\r/)[0] );
- the right one is to get rip of all this bunch of html tag : could you confirm you don't send anything else than the content in your cfc code?
ASKER
We seem to inching closer to a solution here. I tried what you suggested:
res = JSON.parse( res.split(/\r/)[0]);
alert(res);
The alert box had [object][object] in it. So it is indeed an object. I'm not sending anything else in my cfc except for the structure that I mentioned earlier.
res = JSON.parse( res.split(/\r/)[0]);
alert(res);
The alert box had [object][object] in it. So it is indeed an object. I'm not sending anything else in my cfc except for the structure that I mentioned earlier.
res = JSON.parse( res.split(/\r/)[0]);
alert(res.SUCCESS); // or alert(res["SUCCESS"]);
alert(res.SUCCESS); // or alert(res["SUCCESS"]);
>I'm not sending anything else in my cfc except for the structure that I mentioned earlier.
do you've debug mode activated?
do you've debug mode activated?
ASKER
"do you've debug mode activated?"
I'm not sure I follow you. You mean debug option in cf administrator?
I'm not sure I follow you. You mean debug option in cf administrator?
> You mean debug option in cf administrator?
yes
yes
ASKER
I had all the exception checkboxes checked but not the "Enable AJAX debug log window". I checked this and updated. It says cfdebug flag can be passed to view ajax info. How do I do this from the page?
add ?cfdebug
but not this time, we don't want it
if possible paste the full bad JSON object, I think you should be able to read the message (or perhaps with fiddler)
but not this time, we don't want it
if possible paste the full bad JSON object, I think you should be able to read the message (or perhaps with fiddler)
ASKER
OK I got it working with the following code:
res = JSON.parse( res.split(/\r/)[0]);
//alert(res.SUCCESS);
if(res.SUCCESS == true){
ColdFusion.MessageBox.show ('appInfoC hanged');
var updateHField = $("#h_appold");
updateHField.value = $("#txt_racename").val();
return true;
}
else{
alert('Error Occurred in updating Acronym!');
return false;
}
A quick question though: what does res = JSON.parse( res.split(/\r/)[0]); do? What is the split function doing?
res = JSON.parse( res.split(/\r/)[0]);
//alert(res.SUCCESS);
if(res.SUCCESS == true){
ColdFusion.MessageBox.show
var updateHField = $("#h_appold");
updateHField.value = $("#txt_racename").val();
return true;
}
else{
alert('Error Occurred in updating Acronym!');
return false;
}
A quick question though: what does res = JSON.parse( res.split(/\r/)[0]); do? What is the split function doing?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thanks much for sticking though with this!
$.ajaxSetup({ "error": myErrorHandler2 });
updateAppName = function(pid){
$.getJSON("/assets/cfc/myC
}