Showing posts with label coldfusion. Show all posts
Showing posts with label coldfusion. Show all posts

Wednesday, February 27, 2008

Five basic Ajax tutorials

Are you a PHP developer and an Ajax newbie?

This post is a collection of five basic and most required Ajax tutorials with PHP. It inlcudes login, insert record into a database table, search engine, autosuggest and Edit in Place.


Login using AJAX and PHP
This tutorial explains how to implement a simple user login with Ajax and PHP.

Using prototype.js to add record into database with ajax
How to use prototype.js framework to enable a simple ajax request which add a new record (an user name) into a database table using PHP like server side language.

A simple search engine in Ajax and PHP
How to realize a simple search engine with Ajax and PHP that search an user name inside a db table "USER" and return results while you type into the input field.

Search with autosuggest feature
This tutorial explains how to implement a simple PHP ajax search with autosuggest feature using some lines of code.

Edit in place with Scriptaculous and PHP
How to implement a simple Edit in Place effect (Flickr-like) using Scriptaculous and PHP.
Related content
Table of content

Wednesday, February 6, 2008

Search with autosuggest feature (Coldfusion)

Are you a Coldfusion developer? This tutorial help you to implement autosuggest feature for your website using Ajax.

Some days ago I wrote a post about this topic using PHP like server-side language and some readers asked to me how to implement the same ajax search with auto-suggest feature using Coldfusion.


Download this tutorial

How it works
The package contains:

- index.cfm (search form)
- search.cfm (Coldfusion code to execute query)
- ajax_framework.js (javascript functions to enable ajax feature)

When an user type a string in the input field with id "search-q" (in index.cfm) the function autosuggest() searches the current string into a database table...

<input name="search-q" id="search-q" type="text" onkeyup="javascript:autosuggest()"/>
<div id="results"></div>

... and the script shows search results into the <div> layer with id "result".

All files are fully customizable and ready to use in your coldfusion project. Remeber to change SQL code and datasource name in search.cfm using your correct datasource name.

Download this tutorial

Tuesday, January 8, 2008

Split text string using Coldfusion

This tutorial explains how to split an input text string (with some values comma separed) using Coldfusion.


The code is very simple (you can use insted of input string tag_source equal to 'database, mysql, tutorial, how-to' another value such as a #FORM# variable):

<!--- String to split --->
<cfset tag_source = 'database, mysql, tutorial, how-to'>

<cfset comma_pos = -1>
<cfset index = 1>
<cfset tag_array = ArrayNew(1)>
<cfloop condition= "comma_pos NEQ 0 AND len(tag_source) GT 0">
<cfset comma_pos = #find(",", tag_source)#>
<cfif comma_pos NEQ 0>
<cfif comma_pos EQ 1>
<cfset tag_source_n = #left(tag_source, comma_pos)#>
<cfelse>
<cfset tag_source_n = #left(tag_source, comma_pos-1)#>
</cfif>
<cfset tag_source = #removechars(tag_source, 1, comma_pos)#>
<cfset tagArray[index] = trim(tag_source_n)>
<cfelseif comma_pos EQ 0 AND len(tag_source) GT 0>
<cfset tagArray[index] = trim(tag_source)>
</cfif>
<cfset index = index+1>
</cfloop>

<!--- Do something with splittet tags --->
<cfloop from="1" to="#arrayLen(tagArray)#" index="i">
<cfquery name="insertTag" datasource="aigers">
INSERT INTO TAG (tag)
VALUES (
'#tagArray[i]#'
)
</cfquery> </cfloop>

Tuesday, December 18, 2007

Edit in place with Scriptaculous and Coldfusion

After my previous post about this topic (but with PHP instead of Coldfusion) I received some requests about how to implement "Edit in place" Scriptaculous effect using Coldfusion. The structure of this tutorial is the same seen in the previous post with PHP.

Step 1: index.cfm
Create a new blank page, index.cfm. The file's structure is the following:


It contains a link to prototype.js and to scriptaculous framework. The will contains just some lines of code with a layer which contains the text you want to modify with "Edit in Place". So, open index.cfmand add this code into tag:

<div id="myText">This is my text to modify with edit in place</div>
<script>
new Ajax.InPlaceEditor($('myText'), 'javascript:saveText("myText")', {
ajaxOptions: {method: 'get'}
});
</script>

DIV layer (with ID myText) contains text you want to modify using edit in place effect using Scriptaculous. You can also use other tags like <span>, <h1>, to contain the text to modify with edit in place. The code into <script> tag enables Edit in Place function for the content of the layer with ID myText. You can apply the same code to other HTML elements just changing the ID reference "myText" (in bold).

Step 2: ajax_framework.js
In the Step 2 of the PHP tutorial change this code's line into the function saveText():

http.open('get', 'save_text.php?newText='+textId_n+'&nocache = '+nocache);

... with:

http.open('get', 'save_text.cfm?newText='+textId_n+'&nocache = '+nocache);


Step 3: save_text.cfm
Create a new file called save_text.cfm and copy and paste this code inside itself:

<cfif isDefined('URL.newText')>
<cfquery datasource="mydatasource">
INSERT INTO MYTABLE (newText)
VALUES(#URL.newText#)
</cfquery>
<cfoutput>#URL.newText#</cfoutput>
<cfelse>
Error, please fills all fields!
<cfif>

If new value is blank, you have a message error, otherwise the new value will be saved into our database.

Saturday, December 8, 2007

Simple newsletter system using Coldfusion

If you have a website it can be useful to mantain contacts with your users and send periodically some news from your site. Image you have a database with a table USER and some fileds like name and email. This lesson explains how to implement a simple newsletter system using Coldfusion and <cfmail> tag.

Download Tutorial


Step 1: Add form fields
Create a coldfusion blank page and add the following code to the new page:

<form name="insert" id="insert" method="post" action="newsletter.cfm">
<input name="mailObject" type="text" id="title" size="60">
<textarea name="mailText" cols="60" rows="10" wrap="soft" ></textarea>
<input name="submit" type="submit" value="Submit">
</form>


This code adds a field to insert the object and a textarea to insert the text for your message.

Step 2: Coldfusion code to send the message to all users
Add the following code before the <form> tag seen in the previous step:

<cfif isDefined('FORM.submit')>
<!---Set error = 1 if object field and text field are empty--->
<cfif FORM.mailObject EQ ' ' OR FORM.mailText EQ ' '>
<cfset error = 1>
<cfelse>
<cfquery name="getEmail" datasource="myDatasource">
SELECT *
FROM USER
</cfquery>
<!---If error is not = 1, send the message to all users --->
<cfloop query="getEmail">
<cfmail
to="#getEmail.email#"
from="myemail@mysite.com"
subject="#FORM.mailObject#"
replyto="myemail@mysite.com">

Hello #getEmail.name#,

#FORM.mailText#

*********************

Add other infos here like site address, email to contact you...

</cfmail>
</cfloop>
<!---Set error = 0 if object field and text field are not empty--->
<cfset error = 0>
</cfif>
</cfif>

When you submit the form in the step 1, the code execute a query which gets all email address and names of the users stored in your database and execute a loop to send, to each of them, your message. Remember, you have to change datasource name with your datasource name and <cfmail> parameters from nad replyto with your email address.

Wednesday, November 28, 2007

Coldfusion VS PHP part 1

I love Coldfusion. I think, it is the more simple and powerful language to develop web application, but in some cases, expecially when you have to develop a "dynamic" site - let me pass this term... - for a small client, it can't be the better solutions in terms of cost if compared with PHP. This is a first post that evidences some basic differences between two programming languages such as variables and queries for all programmers that, for necessity, have to migrate from Coldfusion to PHP.

Variables
Coldfusion variables are set with <cfset> tag. In PHP, a variable is set inside a <?php ...?> block of code with a "$" char before the var name. For example:

Coldfusion: <cfset myVar = 0>
PHP: <?php $myVar = 0?>

Differences between URL variables:

Coldfusion: #URL.myVar#
PHP: $_GET['myVar'];

Differences between POST variables:

Coldfusion: #POST.myVar#
PHP: $_POST['myVar'];


Execute a query
Coldfusion queries are "beautiful" :) and very simple to define with <cfquery> tag. You have only to specify a datasource name (database you use in your application) and a query name:

<cfquery datasource="myDatasource" name="getUser">
SELECT * FROM USER
</cfquery>


If you use PHP, when you add a query, you have to include in your page all the parameters to connect to database. I suggest to read this post to have more info about this topic. A tipical query in PHP is structured in this way:

<?php
// Connection's Parameters
$db_host="localhost";
$db_name="database_name";
$username="database_username";
$password="database_password";
$db_con=mysql_connect($db_host,$username,$password);
$connection_string=mysql_select_db($db_name);
// Connection
mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);

// Query
$sql = 'SELECT * FROM USER';
$getUser = mysql_query($sql);
?>


How you can see, I defined a variable $sql (with the query SQL code). mysql_query($sql) execute the query.


Query results
After the execution of a query you would show the query results. With coldfusion you ca use <cfouptut> tag and add the "query" parameter to specify what query's result you want to display.

<cfoutput query="getUser">
#name#, #email#, #city#
</cfoutput>


You can also use this dotted code if inside a <cfoutput> code you want to display results from different queries:

<cfoutput>
#getUser.name#, #getUser.email#, #getCity.city#
</cfoutput>


With PHP you have use mysql_fetch_array() method inside a while statement:

<?php
while ($row = mysql_fetch_array($getUser)){
echo $row['name'] . ',' ;
echo $row['email'] . ',' ;
echo $row['city'] . ',' ;
}
?>


I hope this post about this topic can be useful to all PHP/Coldfusion beginner developers. I will add other infos in the next posts.

Sunday, November 25, 2007

Simple 5 stars rating script using AJAX and Coldfusion

This lesson explains how to implement a simple 5 stars rating script using Ajax and Coldfusion. The following picture shows the tutorial structure that we will use to realize this script:




Step 1: Define graphic elements (CSS)

save this image and save it into the pic folder of your website.

Now, create a new css file (default.css) into css folder of your website ad copy and paste this code to create two layer div.star_y (star on), div.star_n(star off):

div.star_y{width:10px; height:10px; background:url(../pic/vote_star.gif); float:left;}
div.star_n{width:10px; height:10px; background:url(../pic/vote_star.gif) 0 10px; float:left;}


Step 2: Define graphic elements: (HTML)
Image you want to use this 5 stars rate script to rate posts in your blog. You have a query that return all posts' titles with the current rate (post rate) and show one or more stars "on" in this way:

5 stars rating script using Ajax
post rate 3/5

First, add a link to the css file adding this line of code into <head> page's tag:

<link href="css/default.css" rel="stylesheet" type="text/css" />


... so, copy and paste this code into index.cfm:

//include ajax_framework.js
<script language="javascript" src="ajax_framework.js">
<cfquery datasource=
"mydatasource"&gt name="getPosts">
SELECT id_post_pk, post_rate, title
FROM MYPOST
</cfquery>
<cfoutput&gt query="getPosts">
#title# <br/>
<cfloop from="1" to="5" index="i"&gt;
<div class="star_<cfif post_rate GE i>y<cfelse>n</cfif>" id="#id_post_pk#_#i#" onmouseover = "javascript:overstar(#id_post_pk#,#i#)" onmouseout = "javascript:outstar(#id_post_pk#,#post_rate#)">
// use a spacer image into the layer
<a href="javascript:ratestar(#id_post_pk#,#i#)">
<img src="pic/spacer.gif"/>
</a>
<br/>
</cfloop>
post rate: <strong>
<span id="rate_#id_post_pk#">#post_rate#</span>/5
<strong>

</cfoutput>



Step 3: Javascript Functions
Create a new javascript file ajax_framework.js and add the following code.
This is the code of javascript functions overstar() and outstar():

/* star "on" on mouse over */
function overstar(idElement,rate){
for(i=1; i<=5; i++){
if(i <= rate){
document.getElementById(idElement+'_'+i).style.backgroundPositionY = "20px";
} else {
document.getElementById(idElement+'_'+i).style.backgroundPositionY = "10px";
}
}
}
/* star "off" on mouse out */
function outstar(idElement,rate){
if(outstar_check == 0){
rate = rate;
}
else {
rate = rateN;
}

for(i=1; i<=5; i++){
if(i<=rate){
document.getElementById(idElement+'_'+i).style.backgroundPositionY = "30px";
} else {
document.getElementById(idElement+'_'+i).style.backgroundPositionY = "10px";
}
}
}


... and this is the code to use AJAX functionality to save vote and calculate the new rate:

var idElementN=0;
var rateN=0;
var nocache=0;
var outstar_check=0;

function rateStar(idElement,rate){ // idElement is the id_post_pk
idElementN=idElement;
rateN=rate;
outstar_check=1;
nocache=Math.random();
http.open('get', 'ratePost.cfm?idElement='+idElement+'&rate='+rateN+ '&nocache='+nocache);
http.onreadystatechange = ratestarReply;
http.send(null);
}
function rateStarReply() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('rate'+idElementN).innerHTML = response;
} }


Step 4: Coldfusion code: ratePost.cfm
rateStar() function send data to ratePost.cfm page to calculate the new rate after a vote. So create this page and copy and paste this code:

<cfset element = #URL.idElement#>
<cfset rate = #URL.rate#>
// get total votes and current rate
<cfquery datasource="mydatasource"&gt name="getTotalVotes">
SELECT total_votes, total_value, post_rate
FROM MYPOST
WHERE id_post_pk = #element#
</cfquery>
// calculate new rate
<cfset newRate = (#getTotalVotes.total_value# + #rate#)/(#getTotalVotes.total_votes# + 1)>
// update rate
<cfquery datasource="mydatasource"&gt name="updateRate">
UPDATE MYPOST
SET post_rate = #newRate#,
total_value= (#getTotalVotes.total_value#+#rate#),
total_votes= (#getTotalVotes.total_votes# + 1)
WHERE id_post_pk = #element#
</cfquery>
// return new rate
<cfoutput>#newRate#</cfoutput>


Save all and try it!

Friday, November 23, 2007

Remove HTML tags from input field using Coldfusion and ReReplace() function

If you develop web applications can be useful take a mind some little sagacity to avoid ugly surprises, for example that an user can add and save javascript code into a form that executes undesired actions.

A typical situation
Image you have a form with an input field where a registered user can add/modify his name:

<cfif isDefined('FORM.name')>
<cfquery datasource="
myDatasource">
INSERT INTO USER (NAME) values (#FORM.name#)WHERE ID_USER_PK = 1
</cfquery>
</cfif><form action="thisPage.cfm"><input name="name"/> <input type="button" value="save" name="submit"/></form>

... an user in vein of jokes could add and save into the database this code:

<script language="javascript">
alert('Site's webmaster is an idiot!');
</script>

... or a loop like this:

<script language="javascript">
for(i=1; i<2000000; i++){ alert('Site's webmaster is an idiot!');} </script>


So, when an user open the page instead of show the name, the browser executes a javascript code that could cause a little embarrassment for the site's webmaster :)
These are just two banal examples but you can find a lot of situations where is very important to do a check of the input data and remove all HTML tags using this simple Coldfusion function:


ReReplaceNoCase(#inputString#,"<[^>]*>","","ALL")


...where #inputString# is the string you want to clear, and "ALL" repeat the same action for all occurrences. You can specify also what tags will be removed, for example if you want to delete only the content inside <script> tag (because you want mantain some no-dangerous HTML tag like <b>, <strong>, <em>), you have to modify the previous code with the following:


ReReplaceNoCase(#inputString#,"<script>.*</script>", "", "ALL")


Remove HTML tags from the previous example
To solve the problem in the previous example, you have to add just a line of code (in bold) inside your page:


<cfif isDefined('FORM.name')>
// remove all html tags in the input string in this case a FORM variable
<cfset nameNOHTML = ReReplaceNoCase(#FORM.name#,"<[^>]*>","","ALL") />
<cfquery datasource="myDatasource">
INSERT INTO USER (NAME) values (#nameNOHTML#)
WHERE ID_USER_PK = 1
</cfquery>
</cfif>
<form action="thisPage.cfm">
<input name="name"/> <input type="button" value="save" name="submit"/>
</form>


In this way all HMTL tags will be removed from the input data.

Tuesday, November 20, 2007

Populate a "select" form with a SQL query using coldfusion

In this post I replied to some reader that have asked to me how to populate a select form element with the results of a SQL query using PHP. I received the same question about how to do the same action using Coldfusion.

Image a simple SQL query which get all users' names on a generic database's table, in this case USER, which have two attributes: ID_USER_PK (primary key) and NAME (the user name):

<cfquery datasource="mydatasource" name="getUser">
SELECT * FROM USER
</cfquery>

Now, to display the query's results into a SELECT form you can use this simple code with <cfoutput query="queryName">:

<select name="select" name="userName">
<cfoutput query="getUser">
<option value="#id_user_pk#">#name#</option>
</cfoutput>
</select>



If you have a parameter in input, for example a URL variable, idUser:

#URL.idUser#


...passed to the page in this way:

http://localhost/index.php?idUser=1


<select name="select" name="userName">
<cfoutput query="getUser">
<option value="#id_user_pk#" <cfif #URL.idUser# EQ #id_user_pk#>selected="selected"</cfif>>#name#</option>
</cfoutput>


In this way, you force to set the "selected" attribute, in your SELECT form, equal to "selected" if the current record has an id_user_pk equal to the parameter in input.

Are you a PHP developer? Read here the PHP version of this post

Wednesday, November 14, 2007

Custom script to calculate a digg-like date difference with Coldfusion

This post explains how you can develope a coldfusion script that calculates difference between two date (the current date, and a reference date) and display the difference in a digg-like style:

2 hour and 10 mins ago


Download Tutorial

Coldfusion code
The code is very simple. You don't have to change nothing, a part #reference_date_here# (in bold) with a reference date, for example the date of a post in your blog.

<cfset currentTime = now()>
<cfset referenceDate = #reference_date_here#>
<cfset difference = dateDiff('n',referenceDate, currentTime)>
<!--- Hours --->
<cfif difference GT 59>
<cfset minuts = difference>
<cfset difference = dateDiff('h',referenceDate, currentTime)>
<cfset divisione = nt(minuts/60)>
<cfset currentMinuts = minuts - (divisione*60)>
<cfif difference EQ 1>
<cfset textDifference = ' hour and '&currentMinuts&' mins ago'>
<cfelse>
<cfset textDifference = ' hours and '&currentMinuts&' mins ago'>
</cfif>
<cfset datadifference = difference&textDifference>
<!--- Days --->
<cfif difference GT 24>
<cfsetdifference EQ 1>
<cfset textDifference = ' day ago'>
<cfset>
<cfsettextDifference = ' days ago'>
</cfif>
<cfset difference = dateDiff('d',referenceDate, currentTime)>
<cfset datadifference = difference&textDifference>
</cfif>
<cfelse>
<cfset datadifference = difference&' mins ago'>
</cfif>

Tuesday, November 6, 2007

A simple search engine in Ajax and Coldfusion

In the previous lesson we have seen how to implement a simple search engine using Ajax and PHP. This is a "variation" for coldfusion lovers :)

Download tutorial


Step 1: main page
Repeat step 1 of previous lesson.

Step 2: Javascript function
Change this code line:

http.open('get', 'in-search.php?name='+searchq+'&nocache = '+nocache);

... with:

http.open('get', 'in-search.cfm?name='+searchq+'&nocache = '+nocache);


Step 3: search into database
Now create a blank .cfm page in-search.cfm and copy and paste this code inside of the page:

<cfquery name="getName" datasource="myDatasource">
SELECT * FROM USER
WHERE name LIKE '%#URL.searchq#%'
</cfquery>
<cfoutput query="getName">
#name#
</cfoutput>


The code is very simple. #URL.searchq# is a Coldfusion URL variable passed from javascript function searchNameq() to coldfusion server. How you can see, the structure is the same of previous post using PHP.

Tuesday, October 23, 2007

Insert record into database using Ajax and Coldfusion

In the previous lesson we have seen how to use Ajax to insert a record into a database table using PHP. In this lesson we will explain how to implement the same tutorial using Coldfusion instead of PHP.

Download tutorial

How it works?
The structure is the same of the previous post. We have:
  1. index.cfm (contains a simple form with an input text)
  2. ajax_framework.js (the javascript function to enable ajax functionalities)
  3. insert.cfm (the Coldfusion code to save the record into a database table)

We have seen how that index.cfm and ajax_framework.js are indipendent from the script language (PHP, ASP, Coldfusion...).

Step 1: index.cfm
This is the code for index.cfm: a simple form that calls (in the action attribute) a javascript function, insertRecord(), in ajax_framework.js.

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

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

<!-- Form: the action="javascript:insert()"calls the javascript function "insert" into ajax_framework.js -->
<form action="javascript:insert()" method="post">
<input name="site_url" type="text" id="site_url" value=""/>
<input name="site_name" type="text" id="site_name" value=""/>
<input type="submit" name="Submit" value="Insert"/>
</form>


How you can see, nothing is changed respect to index.php of the previous post.

Step 2: the javascript function insert() in ajax_framework.js

In this 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 insert():

/* -------------------------- */
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var site_url= encodeURI(document.getElementById('site_url').value);
var site_name = encodeURI(document.getElementById('site_name').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'insert.cfm?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('insert_response').innerHTML = 'Site added:'+response;
}
}


How you can see, the only change, respect to insert() function of the previous tutorial is:

http.open('get', 'insert.cfm?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);


...instead of:

http.open('get', 'insert.php?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);


Step 3: insert.cfm


<cfif isDefined('URL.site_url') AND isDefined('URL.site_name')>
<cfset site_url= #URL.site_url#gt;
<cfset site_name= #URL.site_name#gt;
<!--- Change myDatasourceName with your datasource --->
<cfquery datasource="myDatasourceName">
INSERT INTO SITE (site_url, site_name) VALUES (
"#site_url#",
"#site_name#"
</cfquery>
<!--- Show the site name for the ajax response --->
<cfoutput>#site_name#</cfoutput>
<cfelse>
Error! Please fill all fields!
</cfif>


Save alla and try it in your localhost server.

Wednesday, October 17, 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.