Simple example of a Form post to ColdFusion with jQuery - Login

A few days ago I blogged a simple example of doing an Ajax form post with jQuery to a ColdFusion page. Today I’d like to build upon that simple example by demonstrating a login process that uses jQuery to fire off the authentication requests. I know I keep saying this, but do remember that this is just one way to do this and you could modify this code quite a bit if you wanted it to run a bit differently. Let’s start with a simple Application.cfc file for my application.

<cfcomponent output="false">
	
	<cfset this.name = "jqlogin">

	<cfset this.sessionManagement = true>
	
	<!--- Run before the request is processed --->
	<cffunction name="onRequestStart" returnType="boolean" output="false">
		<cfargument name="thePage" type="string" required="true">
		<cfset var page = listLast(arguments.thePage,"/")>

		<cfif not listFindNoCase("login.cfm,auth.cfc",page)>		
			<cfif not structKeyExists(session, "loggedin") or session.loggedin is false>
				<cflocation url="login.cfm" addToken="false">
			</cfif>
		</cfif>
		<cfreturn true>
	</cffunction>

	<!--- Runs when your session starts --->
	<cffunction name="onSessionStart" returnType="void" output="false">
		<cfset session.loggedin = false>
	</cffunction>

</cfcomponent>

There are two methods defined in this Application.cfc. The important one is the onRequest. It will be used to handle security for the application. If the request is not for my login page or my authentication CFC, and if you aren’t logged in (notice I check a session variable initialized in the onSessionStart), then we push the user to the login page.

Now let’s look at auth.cfc:

<cfcomponent>

<cffunction name="processLogin" access="remote" output="false" returnType="string">
	<cfargument name="username" type="string" required="true">
	<cfargument name="password" type="string" required="true">
	
	<cfif arguments.username is "mcp" and arguments.password is "tron">
		<!--- store login success in session --->
		<cfset session.loggedin = true>
		<cfreturn "success">
	<cfelse>
		<cfreturn "failure">
	</cfif>
</cffunction>
	
</cfcomponent>

Obviously a real authentication CFC would have a bit more to it. This one simply checks for a hard coded username and password. Depending on if these values are specified correctly, the CFC will either return the word failure, or return success while also setting the session variable. Oh, and of course, I set the method to have remote access. (And yes, I did almost forget that.)

Ok, so far, nothing really special has been done. Let’s look at login.cfm and how I used jQuery.

<html>

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>

function sendForm() {
	$("#status").html('Logging in...');
	$.post('auth.cfc?method=processLogin&returnFormat=plain',$("#loginForm").serialize(),function(data,status){
		data = $.trim(data)
		if (data == 'failure') {
			$("#status").html('<b>Your login failed...</b>');
		} else {
			//good login
			$("#status").html('');

			document.location.href='index.cfm'
		}

   });

   return false
   
}

$(document).ready(function() {
   $("#loginForm").submit(sendForm)
})

</script>
</head>

<body>

<form id="loginForm">
   Username: <input type="text" name="username"><br/>
   Password: <input type="password" name="password"><br/>
   <input type="submit" value="Login" />
</form>

<div id="status"></div>

</body>

</html>

Let’s take this from the bottom up. At the bottom of my page I have my login form with two simple fields. Below that I have a blank div with the id of status.

Moving up into the script code block, notice the my document.ready code simply hijacks the form’s submit action. The send form should look pretty familiar to the one I did in the last blog entry. I start off by creating a message in the status div. This will let my users know that something is going on. Next, I use the built in serialize() function to convert the form into data and send it to my ColdFusion code. This time I’m posting to a CFC method, so I specify a returnFormat to keep the result in simple text. If a failure was returned, I set a message in the status div. If the result was good, I clear the status and then send the user to the home page. Why clear the status? If the home page takes a few seconds to load, I don’t want the user to think that their login failed.

That’s it. You can demo this here: http://www.coldfusionjedi.com/demos/jqlogin. I've also attached the files to this blog entry.<p>Download attached file. Old demo links removed on 8/29/2017.</p>

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate looking for his next gig. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments