Coldfusion

You are currently browsing articles tagged Coldfusion.

The following post contains information on how to use jQuery and cfc to populate a select box with data.

The requirements are Coldfusion server 8+

You can download the latest Jquery from here.
You can download a development server from here.

I was looking over the internet for any posts on how to make an ajax call to a cfc and then populate the results to a select box.
My example will show how to populate names of cities depending on the country selection.

Firstly you must create a table called tblCountries and another one called tblCities in your database.
If you spend some time googling around you can find all the data you need easily.

Then we need a coldfusion component (cfc).
The code for the cfc is

Coldfusion component CountriesCities.cfc


<cffunction access="public" name="CountriesList" output="false" returntype="query">
<cfquery name="SelectAllCountries" datasource="#Session.DSN#">
SELECT * FROM tblCountries
ORDER BY title
</cfquery>
<cfreturn SelectAllCountries>
</cffunction>
<cffunction access="public" name="SelectedCities" output="false" returntype="query">
<cfargument name="CountryID" required="yes" type="numeric" default="-23" />
<cfquery name="SelectCities" datasource="#Session.DSN#">
SELECT * FROM tblCities
WHERE <cfif Arguments.CountryID neq -23>CountryID = #Arguments.CountryID#</cfif>
ORDER BY CityTitle
</cfquery>
<cfreturn SelectCities>
</cffunction>

There are two methods. The first method is used when the page loads in order to fill the first select box with country-related data. Then the story is more or less as you might expect: Once a country is selected the second method of the cfc will give us back a result with cities that belong to the selected country.

Now we need to write some html in order to have a form with these two select boxes.

The HTML code is:
HTML code


<cfsilent>
<cfinvoke component="Countries" method="CountriesList" returnvariable="CountriesList"/>
</cfsilent>
<label for="CountriesList">Select Country:</label>
<select name="CountriesList" id="CountriesList">
<option value="" selected="selected">...</option>
<cfloop query="CountriesList"><option value="#CountryID#">#CountriesList.CountryTitle#</option></cfloop>
</select>
<label for="SelectedCities">Select City:</label>
<select name="SelectedCities" id="SelectedCities"><option value="">...</option></select>

As you can see so far we have a selected box filled in with all results from our query and an empty one, with no options at all.
Nice and easy but lets go further. For the ajax call we will need a bit of Jquery.

jQuery ajax call to the coldfusion component


<script type="text/javascript">
// <!--
$(document).ready(function()
{

$("#CountriesList").change(function()
{
if($(this).val() != '')
{
$.ajax({
type: "POST",
url: "/_cfc/CountriesCities.cfc?method=SelectedCities",
data: ({
CountryID: $(this).val()
}),
dataType: "xml",
success: function(xml)
{
$('#SelectedCities option').remove();
$(xml).find('record').each(function()
{
$("#SelectedCities").append('<option value="' + $(this).find('cityid').text() + '">' + $(this).find('citytitle').text() + '<\/option>');
});
}
});
}
});

})

// -->
</script>

Let’s explain the code a bit.
It’s a simple jquery ajax call to the cfc component.
We post the selected country id and once we get a success callback we use jquery again to populate the results to the empty select box “SelectedCities”.
It’s really easy, isn’t it?

The only weird thing I may need to mention is that the format that we use for the call is XML and if you noticed my code I used lowercase to find my database fields.

lowercase field name


$(this).find('cityid').text()

That’s it, now you can go on and add more and more filters in order to have a complete form.

I hope you like my post and found this information interesting!

Tags: , ,

00

The following post contains information on how to create a login Air application with Flash Builder 4 using a cfc web service.
You can download the Flash Builder 4 beta from Adobe Labs
More information about the Flex 4.0 SDK can be found here
The requirements are:
- Flash Builder 4 Beta 2
- Coldfusion 8+
- SQL server 2005+

Create a new flex project ‘Login_Webservice_cfc’

01

We first need to create the application layout. We choose the design view to make our life easier (ctrl+`), then drag and drop a Panel component from the Coponents views.

From the Properties View set the Title as ‘Login’ and set width and height as 250,150 respectively. Set the Panel to always be in the center of the screen by selecting the proper checkboxes from the Constrains area and set both values to ’0′.

02

After that, drag and drop a form component inside the panel from the componets view and set width and height to 100%. We next need to add two TextInput components; one for the Username and one for the Password inputs.

When you add a form component using the design view, Flash builder adds a FormItem wraper for you. So the code for each of your inputs will be similar to this:

Formitem


<mx:FormItem label="FirstInput">
    <s:TextInput id="FirstInput"/>
</mx:FormItem>

Set the labels and IDs using proper values (for the example I use ‘Username’ and ‘Password’ respectively).
At the end you will need a submit button to handle the form submission. Drag and drop a button from the component view below the two text inputs. Use the ‘SubmitBtn’ as an ID value and the ‘Login’ as label value.
As you can see, you need to remove the label value from the submit button FormItem. Click on it and just remove it.

The Login panel should look like this:
03

and the mxml code like this:

Panel component code


<s:Panel width="250" height="150" title="Login" horizontalCenter="0" verticalCenter="0">
<mx:Form width="100%" height="100%" left="0" top="0">
<mx:FormItem label="Username">
<s:TextInput id="Username"/>
</mx:FormItem>
<mx:FormItem label="Password">
<s:TextInput id="Password"/>
</mx:FormItem>
<mx:FormItem>
<s:Button id="SubmitBtn" label="Login"/>
</mx:FormItem>
</mx:Form>
</s:Panel>

If you build your application you will see that everything looks fine except for the password input that needs to display its value as password rather than as normal text. All you need is to add this as an input attribute:
displayAsPassword=”true

Now we need to connect our application to a Web service. For this example I use a coldfusion component (cfc). This is the code for my coldfusion component (.cfc):

Cfc component source


<cfcomponent output="false">
<cffunction access="remote" name="Authenticate" output="false" returntype="struct" hint="This Component authenticates User Accounts">
<cfargument name="Username" required="yes" type="string" />
<cfargument name="Password" required="yes" type="string" />

<cfquery name="Login" datasource="#Session.DSN#">
SELECT * FROM tblLogin
WHERE Username = '#Arguments.Username#'
AND Password = '#Arguments.Password#'
</cfquery>

<cfset ReturnObj = structNew() />
<cfif Login.recordcount gt 0>
<cfset ReturnObj.Success = true />
<cfset ReturnObj.Message = "Login successfull" />
<cfset ReturnObj.ReturnCode = 1 />
<cfset ReturnObj.Username = #Login.AccountName# />
<cfset ReturnObj.Password = #Login.AccountSurname# />
<cfelse>
<cfset ReturnObj.Success = false />
<cfset ReturnObj.Message = "Login incorrect" />
<cfset ReturnObj.ReturnCode = 2 />
</cfif>

<cfreturn ReturnObj>
</cffunction>
</cfcomponent>

Save the file as ‘login.cfc’ on your local web server.
You can see that we ask for two required arguments to be passed: Username and Password and then we create a structure and fill in it with some information. If we validate the user we also put the Name and the surname of the user within the structure.

Now I will use the Flash Builder to call the web service. The Flash builder makes our life easier with new functionality. From the Data/Services View, select ‘Connect to Data/Service’ and choose Web Service (the last one on the right hand side) and click next.

Now add the web service path ‘http://localhost/Login_Webservice_cfc/login.cfc?wsdl’, leave the rest of the settings as they are and click finish. Be aware that if the web service is on a remote machine you need to edit the ‘crossdomain.xml’ file for security reasons.

Now in the Data/Services View you can see the cfc method and the two required arguments.
04

Username and Password are required arguments and the return type will be Object, because we set the coldfusion function to use ‘struct’ as returntype.

We are almost there!

Drag the Authenticate function from the Data/Services view and drop it on the Submit button. Flash builder does all the hard work for you: it creates the actionscript classes and adds some pieces of code as well within your mxml file. Flash builder would just have made a submit handler for you and you need to edit it a bit.

Your function should look like this:

Login handler


protected function SubmitBtn_clickHandler(event:MouseEvent):void
{
AuthenticateResult.token = login.Authenticate(Username.text, Password.text);
}

I will edit the code a bit so I can have a result function as well as a custom fault handler function.
I also create some variables to hold the user’s data if the authentication is successful.
The full code will be like this:

Full mxml code


<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
   xmlns:s="library://ns.adobe.com/flex/spark"
   xmlns:mx="library://ns.adobe.com/flex/halo" width="100%" height="100%" xmlns:login="services.login.*">
<fx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectUtil;
import mx.controls.Alert;

private var rs:Object;
private var Success:Boolean;
private var Message:String;
private var ReturnCode:int;
private var FullName:String;

//Failed to connect to the wsdl service
private function GeneralFailed_Handler(e:FaultEvent):void
{
Alert.show(e.fault.faultString, "Error connecting to the service");
}
//Login Handler
private function SubmitBtn_clickHandler(event:MouseEvent):void
{
AuthenticateResult.token = login.Authenticate(Username.text, Password.text);
}
//Result Handler for Account Authentication
private function AuthenticateResult_resultHandler(e:ResultEvent):void
{
//check the result
Alert.show(ObjectUtil.toString(e.result),"Login Results")

rs = new Object();
rs = e.result;
Success = rs['SUCCESS'];
Message = rs['MESSAGE'];
ReturnCode = rs['RETURNCODE'];

if(ReturnCode == 1)
{
FullName = rs['LOGIN']['NAME'] + " " + rs['LOGIN']['SURNAME'];

}else{
Alert.show(Message, "Try Again");
}
}

]]>
</fx:Script>

<fx:Declarations>
<login:Login id="login" fault="GeneralFailed_Handler(event)" showBusyCursor="true"/>

<s:CallResponder id="AuthenticateResult" result="AuthenticateResult_resultHandler(event)"/>
</fx:Declarations>

<s:Panel width="250" height="150" title="Login" horizontalCenter="0" verticalCenter="0">
<mx:Form width="100%" height="100%" left="0" top="0">
<mx:FormItem label="Username">
<s:TextInput id="Username"/>
</mx:FormItem>
<mx:FormItem label="Password">
<s:TextInput id="Password" displayAsPassword="true"/>
</mx:FormItem>
<mx:FormItem>
<s:Button id="SubmitBtn" label="Login" click="SubmitBtn_clickHandler(event)"/>
</mx:FormItem>
</mx:Form>
</s:Panel>
</s:Application>

Now, if you test your application you will see I have put two alert messages, one for a failed login and a general one to display the result of the submission form:
05

I hope you found this interesting and informative! :D

Enjoy!

Tags: , ,