Building AJAX applications with Adobe Spry, ColdFusion, and ...
-
Upload
sampetruda -
Category
Documents
-
view
1.754 -
download
0
Transcript of Building AJAX applications with Adobe Spry, ColdFusion, and ...
Building AJAX applications with Adobe Spry, ColdFusion, and JQuery
Topics
AJAX ToolkitMania!
ColdFusion 8 Key Concepts
Adobe Spry Key Concepts
JQuery Key Concepts
AJAX ToolkitMania!
Every library has core strengths and weaknesses
ColdFusion 8 Ext-JS datagrid <cfinput> bind expressions FCK WYSIWYG editor Perform data fetch with <cfajaxproxy> Virtual windowing API with <cfwindow> Ability to act as a proxy for a data request from a remote domain via <cfhttp> or
<cffeed>
Spry AJAX Toolkit for web designers Easy to use HTML tag markup syntax Powerful layout and effects components Easy to deploy form validation via Dreamweaver CS3/CS4 Compatible with Adobe AIR
JQuery Powerful DOM Maniupulation Robust Plug-in/Extensions library 3rd party support (even Microsoft likes it!) Compatible with Adobe AIR
ColdFusion 8 Key Concepts
Interacting with ColdFusion components via <cfajaxproxy>
Working with bind expressions
<cfajaxproxy>
Quickly and efficiently allows you to make hidden data requests to a ColdFusion component
Once a proxy has been established, you can define a JavaScript error handler that will be triggered if the CFC method fails for any reason
You can also define a success handler that will receive a native Javascript data type returned from your component methods
<cfajaxproxy> example
<cfajaxproxy cfc="employee" jsclassname="cfcEmployee">
<script language="JavaScript">
errorHandler = function(statusCode,statusMsg) { alert(statusCode + ': ' + statusMsg)}
successHandler = function(result) {
var str = ""; for (var i=0; i<result.length; i++) {
str = str + "\t" + result[i].LASTNAME + ',' + result[i].FIRSTNAME + '\n';
}alert("Matches: \n" + str);
}
getName = function() { var username = prompt("Enter the user id",""); if (username != null) {
/* instantiate CFC */var employeeObj = new cfcEmployee(); /* configure responders */employeeObj.setErrorHandler(errorHandler);employeeObj.setCallbackHandler(successHandler)
/* invoke method */employeeObj.getbylastname(username);
}}</script>
Working with BIND expressions
Adobe Spry Key Concepts
Introduction to Spry
Installing Spry
Debugging Spry
Retrieving Data with Spry
Working with Data
Working with JSON
Spry Widgets
UI Widgets
Loading Data into Spry Fields
Posting Form Data from Spry
Introduction to Spry
JavaScript library for web designers providing functionality that allows designers and developers to build pages that provide a richer experience for their user
Designed to bring AJAX to the web design community
Spry's data handling capabilities enable designers to incorporate XML, JSON, and HTML Table data
The Spry framework is HTML-centric, and easy to implement for users with basic knowledge of HTML, CSS and JavaScript
Adobe has included easy to use design-time widgets for Spry into Dreamweaver CS3
Direct support in the Eclipse-based Aptana IDE
Can be used with AIR – the Adobe Integrated Runtime
Installing Spry
Spry is packaged as a zip file, containing a number of JavaScript and CSS files that are necessary for its operation
ArticlesIn-depth articles describing how to use Spry
DataXML data used in the examples
DemosSample applications
IncludesCore Javascript files for accessing data
Includes_minifiedMinified copies of the core JavaScript files where all extraneous white space and comments have been removed, resulting in faster download times.
Includes_packedPacked copies of the JavaScript files
SamplesExamples that focus on a specific component of Spry
WidgetsJS and CSS files for the user-interface components of Spry
Best Practice: create a /SPRYAssets/ directory off of your web root and including the contents of includes_minified, as well as all of the .CSS files from the /Widgets/ folder.
Note that an older version of Spry comes bundled with ColdFusion 8
Debugging Spry
A DOM Element inspector
A line console for interactive debugging
Outputs the contents of any debug.log() invocations that you have in your code.
Implementing the debugger
SpryDebug.css SpryDebug.js
Additional JS Debuggers
FireBug plug-in for Mozilla https://addons.mozilla.org/en-US/firefox/addon/1843
Microsoft Internet Explorer Web Developer toolbarhttp://www.microsoft.com/downloads/details.aspx?familyid=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en
ColdFusion AJAX Debug Log Window(append ?cfdebug to your URL)
Retrieving and Displaying Data with Spry
Generate data from your application server (ColdFusion) in a Spry compatible format (XML, JSON, HTML)
Use the Spry Dataset Constructor to make an http request to your application server that outputs the structured data
Define output areas on your page and how they are to formatted
Periodically refresh data from the server without a full-page reload
Generating data from ColdFusion
All of your business logic and code that accesses "back office" resources should be encapsulated within ColdFusion Component (CFC) methods
<cfcomponent output="false"><cfset dsn = "ftajax100-lab"><cffunction name="get" access="public"
returntype="query"><cfset var q = ""><cfquery name="q"
datasource="#dsn#">select *from [user]
</cfquery><cfreturn q>
</cffunction></cfcomponent>
Generating Data from ColdFusion
Add additional methods to format your queries into XML, JSON
CFC method access type must be set to REMOTE
<cffunction name="getASXML" returntype="xml" access="remote" output="false"> <cfset var q = get()> <cfset var xData = ""> <cfxml variable="xData"> <employees> <cfoutput query="q"> <employee> <lastname>#q.lastname#</lastname> <firstname>#q.firstname#</firstname> <email>#q.email#</email> </employee> </cfoutput> </employees> </cfxml> <cfreturn xData></cffunction>
Making an HTTP Request to Execute a CFC Method
http://[server]/[directory]/employee.cfc?method=getAsXML
Additional parameters to CFC methods can be passed in using standard url syntax:
http://[server]/[directory]/employee.cfc?method=getAsXML¶m1=value1¶m2=value2
Walkthrough 1
Preparing for Development with Spry
Retrieving Data with Spry
Use the Spry Data constructor
The constructor is defined within the sprydata.js file
Additional Spry components must be included, depending on the datatype of the content being fetched
Any attempt to load data from a domain other than the one that your GUI is on will result in a security exception
Use CF as a proxy, if necessary
<script language="JavaScript" src="/SpryAssets/xpath.js"></script><script language="JavaScript" src="/SpryAssets/sprydata.js"></script><script language="JavaScript">var ds1 = new Spry.Data.XMLDataSet( "/ftajax100/data/users.xml","employees/employee");</script>
Working with Spry Data in JavaScript
Outputting the contents of Spry Data
A Spry dynamic region is an area on the page that displays the data and automatically updates the data display whenever the data set is modified
Spry dynamic regions are defined by attaching a spry:region attribute to an html tag. Using spry:region is analogous to using the <cfoutput> tag in ColdFusion
Loop through a Spry dataset by attaching a spry:repeat attribute to a nested html tag
Outputting the contents of Spry Data
<script src="/SpryAssets/xpath.js" language="javascript"></script><script src="/SpryAssets/sprydata.js" language="JavaScript" ></script> <script language="JavaScript"> var ds1 = new Spry.Data.XMLDataSet ("/ftajax100/data/employees.xml", "employees/employee"); </script> <div spry:region="ds1"> <div spry:repeat="ds1"> {ds1::lastname}, {ds1::firstname} </div></div>
(employees.xml)<?xml version="1.0" encoding="utf-8"?><employees xmlns="http://www.foo.com/employees"> <employee id="1"> <lastname>Drucker</lastname> <firstname>Steve</firstname> </employee> <employee id="2"> <lastname>Perry</lastname> <firstname>Jason</firstname> </employee></employees>
Working with Data
XML (Extensible Markup Language)
JSON (JavaScript Object Notation)
HTML tables
Working with JSON
Represents complex data structures as JavaScript variable declarations
When outputting JSON for Spry, you must send a content header of application/json
Simple to deserialize – use the eval() method
Data representation is very lightweight
Easier to manipulate, particularly if they you don't have much experience with XML/XPATH
Generating JSON from ColdFusion
ColdFusion 8 can automatically serialize its native data structures into JSON by using the serializeJSON() function
Note the use of <cfoutput> vs. <cfreturn>
<cffunction name="getAsJSON" access="remote" returntype="void">
<cfargument name="username" type="string" default=""> <cfset var q = ""> <cfquery name="q" datasource="#dsn#"> select * from [user] where 0=0 <cfif arguments.username is not "">
and lastname like <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.username#%"> </cfif> </cfquery> <cfoutput>#serializeJSON(q)#</cfoutput></cffunction>
Retrieving query data serialized as JSON with Spry
Include 2 libraries SpryData.js SpryJSONDataSet.js
You can only access column data by their indicies
You need to specify a filter in order to select only the data, not the column titles.
Use the useCache:false option if your data will be changing frequently.
Using JSON Data
<html><head><script language="JavaScript" src="/SpryAssets/sprydata.js"></script><script language="JavaScript" src="/SpryAssets/SpryJSONDataSet.js"></script><script language="JavaScript">var ds1 = new Spry.Data.JSONDataSet("employee.cfc?method=getAsJSON", {path:"DATA",useCache:false });</script> </head><body><div spry:region="ds1">
<div spry:repeat="ds1"> {ds1::2}, {ds1::1} </div></div> …</body></html>
Refactoring query data for JSON
In the prior example, query columns were referenced by position – not a best practice
Before returning query data as JSON, you reformat it into an array of structures
<cffunction name="getAsJSON" access="remote" output="true" returntype="void"> <cfset var aresult = arraynew(1)> <cfset var q = get()> <cfset var stdata = structnew()> <cfloop query="q"> <cfset stData = structnew()> <cfset stdata.firstname = q.firstname> <cfset stdata.lastname = q.lastname> <cfset stdata.email = q.email> <cfset arrayAppend(aResult,stData)> </cfloop> <cfoutput>#serializejson(aResult)#</cfoutput> </cffunction>
Refactoring Query Data for JSON
<script language="JavaScript" src="/SpryAssets/sprydata.js"></script><script language="JavaScript" src="/SpryAssets/SpryJSONDataSet.js"></script><script language="JavaScript">var ds1 = new Spry.Data.JSONDataSet("employee.cfc?method=getAsJSON" ,{useCache:false }); </script> <div spry:region="ds1"> <div spry:repeat="ds1"> {ds1::LASTNAME}, {ds1::FIRSTNAME} </div></div>
Formatting JSON data into HTML Tables using spry:sort
Allows you to sort data by a specific column or columns.
Columns can be set to sort on up to three fields and you can set the sort order to either ascending or descending
Steps Wrap the entire table in a spry:region tag Placing a spry:repeat into the <tr> tag block that contains
your data. Place a spry:sort attribute into the <th> tags to sort the
recordset and redraw the table.
Using Alternating Row Colors in a dynamic table
Deploy the spry:even attribute into the <tr spry:repeat>
Applies the specified style class to an object if the output row number is even
Conversely, spry:odd will apply a specified style to an object if the row number being output is an odd number.
Spry Table
<html><head><style>.altColor {background-color: yellow;}</style><script language="JavaScript" src="/SpryAssets/sprydata.js"></script><script language="JavaScript" src="/SpryAssets/SpryJSONDataSet.js"></script><script language="JavaScript">var ds1 = new Spry.Data.JSONDataSet("/ftajax100/walk/employee.cfc?method=getAsJSON",{useCache:false });</script></head><body><div spry:region="ds1"><table border="1">
<tr> <th spry:sort="LASTNAME">Last Name</th> <th spry:sort="FIRSTNAME">First Name</th></tr><tr spry:repeat="ds1" spry:even="altColor">
<td>{LASTNAME}</td><td>{FIRSTNAME}</td>
</tr></table></div></body></html>
Walkthrough
Creating Dynamic Tables
Spry Widgets
Spry also supports a number of data-aware user interface "widgets" that allows you to easily enhance the usability of your web application Form Field Replacements User Assistance Widgets User Interface Widgets
Widgets have their own distinct JavaScript library and css file associated with them. Both of these files must be included in order for the widget to function properly.
Demos for each of the widgets are available in the /Spry/Articles/ directory.
Spry Form Field Widgets
Text Field
Password
TextArea
Radio Button
Select Box
Check Box
Confirm Widget
Walkthrough 5-4
Using Spry Validation Text Fields
Spry UI Widgets
Accordion
HTML Panel
MenuBar
Sliding Panels
Collapsible Panel
Tabbed Panel
Tabbed Panels
Horizontal / Vertical Orientation
Include scripts SpryTabbedPanels.css SpryTabbedPanel.js
Tabbed Panels Example
<head>. . .<link href="/SpryAssets/SpryTabbedPanels.css" rel="stylesheet" type="text/css" /><script src="/SpryAssets/SpryTabbedPanels.js" type="text/javascript"></script> </head> <body> <div class="TabbedPanels" id="T1"> <ul class="TabbedPanelsTabGroup">
<li class="TabbedPanelsTab" tabIndex="0"> Tab 1 </li> <li class="TabbedPanelsTab" tabIndex="0"> Tab 2 </li> </ul> <div class="TabbedPanelsContentGroup"> <div class="TabbedPanelsContent"> Tab 1 content </div> <div class="TabbedPanelsContent"> Tab 2 content </div> </div> </div> <script type="text/javascript"> var TabbedPanels1 = new Spry.Widget.TabbedPanels("T1"); </script> </body>
Walkthrough 5-5
Using the Tabbed Panels Widget
Spry Effects
Spry Effects
Additional Spry / ColdFusion 8 Integration Points ColdFusion includes the complete Spry 1.5 framework
release in web_root/CFIDE/scripts/ajax/spry directory
<cfsprydataset> - outputs Spry dataset syntax on a page
ColdFusion <cfinput> tags can use Spry data sets directly in bind expressions
<cfsprydataset> Example
<cfsprydataset name="theItems" type="json" bind="CFC:Employee.get(empid={myform:empid})" options="{usecache:false;}">
Binding Spry Data to <cfinput>
JQuery
Fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development
http://jquery.com
55K in length
<script src="http://code.jquery.com/jquery-latest.js"></script>
JQuery Basics
Basic Syntax / Interacting with other libraries
Using Selectors and Events
Document Manipulation
JQuery Effects
Writing your own extensions
JQuery Basic Syntax
<script src="../scripts/jquery.js" language="javascript"></script><script language="javascript"> jQuery.noConflict(); // avoid name conflict with Spry
jQuery(document).ready(function(){ // essentially a body onload // code goes here });
function fnShowHide() {
var cStyle = jQuery('#somecontent').css('display');if (cStyle == 'block') jQuery('#somecontent').css('display','none');else jQuery('#somecontent').css('display','block');
}</script>
</head><body><div id="somecontent">This is some content</div><form><input type="button" value="Hide/Show" onClick="fnShowHide();" /></form>
Using Selectors and Filters
Selectors Find the first element with the class "myclass"
jQuery(".myClass"); Find the element named "mydiv"
jQuery("#mydiv"); Find every DIV element
jQuery("div"); Match any of the selectors
jQuery("p.t1,p.t2,div,span");
Filters :even :odd :eq(index) :gt(index) :lt (index) :header :animated :contains(text)
jQuery("tr:even").css("background-color", "#bbbbff");
Using Selectors and Filters Example
<script language="javascript" src="../scripts/jquery.js"></script><script language="javascript">
jQuery.noConflict();jQuery(document).ready(function(){
// code goes here });
function fnSelectAll(obj) { jQuery("input[name='topping']").attr("checked",obj.checked); }
</script></head>
<body><form>Select toppings:<br /><input type="checkbox" name="selectall" onClick="fnSelectAll(this)"/>Select All<br /><input type="checkbox" name="topping" value="1" />Pepperoni<br /><input type="checkbox" name="topping" value="2" />Onion<br /><input type="checkbox" name="topping" value="3" />Tomato<br /><input type="checkbox" name="topping" value="4" />Meatball<br /><input type="checkbox" name="topping" value="5" />Squirrel<br /></form>
Walkthrough
Using Selectors
Document Manipulation
html() - extract HTML from matching element jQuery(this).html();
html(val) - set HTML of matching element jQuery(this).html("<h1>Steve was here</h1>");
append(content) - append content to matching elements
prepend(content) - prepend content to matching elements
after(content) - append content to matching elements
remove() - remove matching items from DOM
insertAfter(expr) - insert objects after matching objects
wrap(html) - wrap matching elements with html
replaceWith(content) - replace all matched elements with specified content
clone - clone matched DOM elements
JQuery Effects
show()
hide()
toggle()
animate()
stop()
dequeue()
slideDown()
slideUp()
slideToggle()
fadeIn()
fadeOut()
fadeTo()
<div id="somecontent">This is some content</div><form><input type="button" value="Hide/Show" onClick="jQuery('#somecontent').slideToggle('slow')" /></form>
Walkthrough
jQuery Effects
jQuery background data requests
Able to work around browser domain security issues
jQuery.ajax(options)Load a remote page using an HTTP request
load(url,data,callback)Load HTML from a remote file and inject into the DOM
jQuery.get(url,data,callback,ttype)Load a remote page using an HTTP GET request
jQuery.getJSON(url,data,callback)Get JSON data
jQuery.getScript(url,callback)Loads and executes a JavaScript
jQuery.post(url,data,callback,type)Loads a remote page using HTTP Post
Writing your own JQuery Extensions
Very simple to author plugins:http://docs.jquery.com/Plugins/Authoring
A thousand plugins available at http://plugins.jquery.com/
Putting it all together
Output data from CFC's in JSON format
Use <cfajaxproxy> to make background server requests to ColdFusion
Use <cfgrid> for grid controls
Use <cfwindow> and related API for virtual windowing
Use Adobe Spry form field, interface widgets, and dynamic tables
Get your designers to use Spry via Dreamweaver CS3/CS4
Use jQuery for building mashups from different sites (working around cross-site security issues) and for easy DOM manipulation
Questions?