ColdFusion and AJAX: Example 1

Returning a string with AJAX

Using jQuery/AJAX we can pass information asynchronously to and from a CFC. The hardest part of doing this has always been a Where do I start?. Thankfully, I made a template for creating the AJAX calls to a CFC several years back that covers all of the bases.

In this demo, we are just going to take the information provided by the user, pass it to a CFC function, and simply return the value and do something with it.

The Demo

This is the working demo. Just enter something into the field and mash the Test Me button.

Please enter your name

Notice that the page did NOT refresh. This is the aforementioned passing of info asynchronously. This means the info was passed to the CFC behind the scenes - invisibly. How do we perform this miracle of science? I'll show you...

The HTML

The HTML for the page should just be our standard Bootstrap 4 template. You'll want a copy of my jpBSField custom tag too. More on that tag in another lesson. It's a game-changer for app development. Anyway, then, add the following.

		
<form action="" method="post" novalidate class="needs-validation">
<div class="container">
    <div class="row">
    	<cf_jpBSfield size="6" ID="Foo" name="Foo" type="text" label="Your Name" placeholder="enter your name" required="true" requiredtext="Please enter your name" value="">
			
		<cf_jpBSfield name="test" id="button" type="button" value="Test Me" bscolor="primary" size="6"> 
			
			
		<div class="w-100 my-2"></div>
			
		<div class="col-xl-12">
			<div class="" role="alert" id="mydiv2"></div><!--- Your return info will appear here --->
		</div>
		
    </div>
</div>
</form> 
		
		

The AJAX call...

The AJAX template below is the most basic version of the template I created a few years back. It's very simple. You specify a function trigger - in this case when the Test Me button is clicked. Then pass some info into the CFC and tell the script what you want to do when you get a valid response.

In the case of this script we are just passing the info the user types into the text field into the CFC.

Put this call beneath your script tag calling jQuery. If you look at the source of this page you'll see where I mean....

The // do this stuff when successful section is just creating a Bootstrap alert with plain javascript. The Data variable is the returned data from the CFC. This is where things can be a bit confusing. In the CFC we send back a variable named user. Once that content is returned to the AJAX script it becomes Data, which is being created from the section of the script following the // send the data to the CFC comment. You won't use the user variable anywhere but the CFC.

		
		
<script type="text/javascript">
<!--//
// attach behaviors when DOM is fully loaded
$(document).ready(function (){
	
	
	// JSON pre-processor - Use this when you are prefixing JSON with two slashes at the server or app level
	$.ajaxSetup({
		dataFilter: function(data, type){
			return data.substring(2, data.length);
		}
	});
	// end pre-processor
	
	// when the "Test Me" button is clicked, look up the data
	$("#button").click(function (){
		$.ajax({
			
			
			  url: "comps/test1.cfc", // the location of the CFC to run
			  type: "get", // send a GET HTTP operation
			  dataType: "json", // tell jQuery we're getting JSON back
			// send the data to the CFC
				data: {
				
				  method: "findUser", // the method in the CFC to run
				  // arguments here separated by commas
				  theKeyword: $("#Foo").val(),
				  theDemo: "test"
					//I included this unused variable so you can see the syntax for this section
				},
			// this gets the data returned on success
			success: function (data){
				// do this stuff when successful
				
						document.getElementById("mydiv2").classList.add("alert");
						document.getElementById("mydiv2").classList.add("alert-success");
						var theWords = "Welcome, " + data + "! Nice to meet you!";
						document.getElementById("mydiv2").innerHTML = theWords;
				
			},
			// this runs if an error
				error: function (xhr, textStatus, errorThrown){
				// show error
				alert(errorThrown);
			}
		});
	});
});
//-->
</script>
		
		
		
		

The CFC: test1.cfc

In the case of the CFC, test1.cfc, you just need to create it in a folder named comps. There's no magic to that name - you'll see it is as part of the URL in the jQuery AJAX script above. Heck, you could have a folder named ILoveDillPickles instead - just make sure your code reflects it.

You can see the simple <cfreturn user /> here that sends the user variable back to the AJAX script where it will become the Data variable.

This is the most basic bare-bones CFC function I could create for this demo. It simply takes the incoming argument theKeyword and sends it back to the user. A couple of items to note here:

  1. Check the retuntype of the function - here are sending a string back. You can pass lots of different info formats back to the calling page - the next few demos will cover those.
  2. Note the argument name theKeyword? The variable is the same name as the script variable in the AJAX. Make sure this is always the case.
  3. This is a ColdFusion page. You can process any kind of CFML you need to and pass data back to the calling page. For example, I use this to check for available folder names in the AFIT CMS so when a user needs to create a new subsite it checks the server to see if the folder they want to create exists already.

<cfcomponent output="false">
	<cffunction name="findUser" access="remote" returntype="string" returnFormat="json" output="false">
		<cfargument name="theKeyword" type="string" required="true" />

		<!--- for the case of this simple demo we will just snag the user's input and spit it right back --->
		<cfset user = arguments.theKeyword>

		<!--- Do your CF here --->

		<cfreturn user />
	</cffunction>
</cfcomponent>

Debugging and General Pointers

Debugging is the biggest pain with CFC calls. I generally avoid them simply because they can be such a pain to debug. Fortunately, I have screwed these things up enough that I can direct you in a simple debugging method.

Because the call to a CFC with AJAX is done asynchronously, you don't actually see it happen. It is done silently behind the scenes. Here's how to see the request and response:

  1. In your browser, Chrome, Edge, or Firefox (my weapon of choice) open your developer's console/tools.
  2. Go to the NETWORK tab
  3. It will probably ask you to refresh the page...do that
  4. Enter something into the box and click the test me button.
  5. In dev tools click on the CFC
  6. On the right, click Headers - you can see the URL and values passed to the CFC since we are doing a GET request here.
  7. Now click on the Response tab and you can see the info - including any CF errors - being returned to the page!
  8. Here's a screenshot showing where this is in the Firefox dev tools - it's in almost the same space in Edge and Chrome. Just hit F12 to open them.