Wednesday, 17 October 2007

Login using Ajax and Coldfusion

This lesson will explains how to implement a simple user login with Ajax and Coldfusion.

Download tutorial

Introduction
In the site root we have to create two file, index.cfm and login.cfm and a folder AJAX with ajax_framework.js.


This is the workflow: the user submit an HTML form with the username (in this example is the email address) and password. The form action call a javascript function, login(), in the ajax_framework.js file. This function pass with URL variables the input data to login.cfm page that execute a query and verify if the user exist. If the user exist return the user name, else return 0. The function loginReply() take this value returned from login.cfm and show a message into a layer of index.cfm.



Step 1: the Login HTML Form
The first step is to create the HTML form. How you can see, the code below is indipendent from the server-side scripting language and can be used for example with Coldfusion, PHP and other languages. In the first row we will include ajax_framework.js that contains javascript functions to enable ajax functionalities (XMLHttpRequest and other functions, in this example the login() function):

<!-- Include AJAX Framework -->
<script src="ajax/ajax_framework.js" language="javascript"></script>

<!-- Show Message for AJAX response -->
<div id="login_response"></div>

<!-- Form: the action="javascript:login()"call the javascript function "login" into ajax_framework.js -->
<form action="javascript:login()" method="post">
<input name="emailLogin" type="text" id="emailLogin" value=""/>
<input name="pswLogin" type="password" id="pswLogin" value=""/>
<input type="submit" name="Submit" value="Login"/>
</form>


Step 2: the javascript function Login()
In the previous lesson we have see how enable the XMLHTTPRequest. In ajax_framework.js file we have added this code:

/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();


Now, in the same javascript file, we will add other lines of code for the function login():

/* -------------------------- */
/* LOGIN */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function login() {
// Optional: Show a waiting message in the layer with ID ajax_response
document.getElementById('login_response').innerHTML = "Loading..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var email = encodeURI(document.getElementById('emailLogin').value);
var psw = encodeURI(document.getElementById('pswLogin').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'login.cfm?email='+email+'&psw='+psw+'&nocache = '+nocache);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply() {
if(http.readyState == 4){
var response = http.responseText;
if(response == 0){
// if login fails
document.getElementById('login_response').innerHTML = 'Login failed! Verify user and password';
// else if login is ok show a message: "Welcome + the user name".
} else {
document.getElementById('login_response').innerHTML = 'Welcome'+response;
}
}
}


Step 3: login.cfm
In the previous step we have see how the login() function pass two variable (email and psw) to the page login.cfm, to execute a query into our database and verify that the user exists. This is the login.cfm page code:

<!-- COLDFUSION login.cfm --->
<cfif isdefined('URL.email') AND isDefined ('URL.psw')>
<cfquery name="login" datasource="#dbName#">
SELECT *
FROM USER
WHERE email= '#URL.email#' and psw= '#URL.psw#'
</cfquery>
<!-- If record exists return the user name to the javascript funciont loginReply() -->
<cfif login.recordCount NEQ 0>
#login.name#
<!-- Else if record don't exists return 0 to the javascript function loginReply()-->
<cfelse>
0
</cfif>
</cfif>

Now our first Ajax example is ready to run!

Some details
If you use a DB access and you have a table called USER, when execute a query in the SQL FORM clause use "[USER]" and not only "USER" else you will have an error when coldfusion execute the query.

In the <cfquery name="login" datasource="#dbName#"> I have used a variable name for the datasource (#dbName#). This variable is defined in the Application.cfm file. See this post to more details about a coldfusion site structure. If you don't use a variable for the datasource name, replace with: <cfquery name="login" datasource="myDatasourceName"> where "myDatasourceName" will be the name of your datasource.

No comments:

Post a Comment