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)
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#);" />

Open in new window

LVL 1
roger vAsked:
Who is Participating?
 
leakim971PluritechnicianCommented:
we split the string with/by carriage return \r
so we get an array
we take the first item of this array
0
 
leakim971PluritechnicianCommented:
Look like we can start with this one : http://www.coldfusioning.com/index.cfm/2009/10/29/ColdFusion-and-jQuery--Using-AJAX-to-Call-a-CFC-and-Return-JSON

$.ajaxSetup({ "error": myErrorHandler2 });

updateAppName = function(pid){
     $.getJSON("/assets/cfc/myCFC.cfc", { "method": "funcUpdateAppAcron", "tv": document.getElementById('myInput').value, "te":pid,  "returnformat": "json"  }, updateInfo);
}
0
 
roger vAuthor Commented:
@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?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
leakim971PluritechnicianCommented:
do you have a link to see your page?
0
 
roger vAuthor Commented:
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?
0
 
leakim971PluritechnicianCommented:
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
0
 
leakim971PluritechnicianCommented:
try to see the error with fiddler
0
 
roger vAuthor Commented:
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:


$.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;
}

Open in new window

0
 
leakim971PluritechnicianCommented:
>Fiddler does not show any error

so you see the data?

could you post you entire codes ? cfm and myCFC.cfc?
0
 
roger vAuthor Commented:
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;
}

Open in new window

0
 
leakim971PluritechnicianCommented:
you don't need newNameVal and oldNameVal

line 37 :
$.getJSON("UpdRaceInfo.cfc",{"method":"funcUpdateRace","myarg1":$("#racename").val(),"myarg2":"nothing_just_for_fun","myarg3":te,"returnformat":"json"},updateInfo);

myarg1 is the value of the field racename
myarg2 is not used
te is the value url.processid
0
 
roger vAuthor Commented:
@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.
0
 
leakim971PluritechnicianCommented:
No no it should work I tested it with your code
0
 
roger vAuthor Commented:
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/UpdRaceInfo.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);
}
0
 
leakim971PluritechnicianCommented:
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
0
 
roger vAuthor Commented:
@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.
0
 
roger vAuthor Commented:
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.
0
 
leakim971PluritechnicianCommented:
Try : alert( res.SUCCESS )
Or : alert( eval( "(" + res + ")" ).SUCCESS )
0
 
roger vAuthor Commented:
Nope, neither of them worked. I get a javascript error: object does not support this property
0
 
leakim971PluritechnicianCommented:
could you paste what you get in the alert with :

alert( JSON.stringify( res ) );
0
 
roger vAuthor Commented:
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.
0
 
leakim971PluritechnicianCommented:
forget fiddler, please paste what you get in the alert
0
 
roger vAuthor Commented:
I get a js error:

'JSON' is undefined
0
 
roger vAuthor Commented:
OK, in order to use the json object, i've got to load a json2.js file?
0
 
leakim971PluritechnicianCommented:
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/your/own/json2.js"></script>
0
 
leakim971PluritechnicianCommented:
>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
0
 
roger vAuthor Commented:
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,\"ERRORS\":\"\"}\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?
0
 
roger vAuthor Commented:
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]);
      }
0
 
leakim971PluritechnicianCommented:
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?
0
 
roger vAuthor Commented:
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.
0
 
leakim971PluritechnicianCommented:
res = JSON.parse( res.split(/\r/)[0]);
      alert(res.SUCCESS); // or alert(res["SUCCESS"]);
0
 
leakim971PluritechnicianCommented:
>I'm not sending anything else in my cfc except for the structure that I mentioned earlier.

do you've debug mode activated?
0
 
roger vAuthor Commented:
"do you've debug mode activated?"

I'm not sure I follow you. You mean debug option in cf administrator?
0
 
leakim971PluritechnicianCommented:
> You mean debug option in cf administrator?

yes
0
 
roger vAuthor Commented:
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?
0
 
leakim971PluritechnicianCommented:
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)
0
 
roger vAuthor Commented:
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('appInfoChanged');
            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?
0
 
roger vAuthor Commented:
thanks much for sticking though with this!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.