Solved

Making an ajax call with jQuery in Coldfusion 9

Posted on 2011-09-15
38
311 Views
Last Modified: 2012-05-12
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

0
Comment
Question by:roger_v
  • 19
  • 19
38 Comments
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
@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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
do you have a link to see your page?
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
try to see the error with fiddler
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
>Fiddler does not show any error

so you see the data?

could you post you entire codes ? cfm and myCFC.cfc?
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
@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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
No no it should work I tested it with your code
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
@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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
Try : alert( res.SUCCESS )
Or : alert( eval( "(" + res + ")" ).SUCCESS )
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
Nope, neither of them worked. I get a javascript error: object does not support this property
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
could you paste what you get in the alert with :

alert( JSON.stringify( res ) );
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
forget fiddler, please paste what you get in the alert
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
I get a js error:

'JSON' is undefined
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
OK, in order to use the json object, i've got to load a json2.js file?
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
>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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
res = JSON.parse( res.split(/\r/)[0]);
      alert(res.SUCCESS); // or alert(res["SUCCESS"]);
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
>I'm not sending anything else in my cfc except for the structure that I mentioned earlier.

do you've debug mode activated?
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
"do you've debug mode activated?"

I'm not sure I follow you. You mean debug option in cf administrator?
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
> You mean debug option in cf administrator?

yes
0
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 1

Author Comment

by:roger_v
Comment Utility
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
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
Comment Utility
we split the string with/by carriage return \r
so we get an array
we take the first item of this array
0
 
LVL 1

Author Closing Comment

by:roger_v
Comment Utility
thanks much for sticking though with this!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

CFGRID Custom Functionality Series -  Part 1 Hi Guys, I was once asked how it is possible to to add a hyperlink in the cfgrid and open the window to show the data. Now this is quite simple, I have to use the EXT JS library for this and I achiev…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now