Implementing Ajax In ColdFusion 7

38
Harbinger Systems Implementing Ajax in CF7 Basic and Intermediate Level using JavaScript, JSON and ColdFusion 7 Pranav Prakash ([email protected])

description

Ajax 101 in ColdFusion 7

Transcript of Implementing Ajax In ColdFusion 7

Page 1: Implementing Ajax In ColdFusion 7

Harbinger Systems

Implementing Ajax in CF7

Basic and Intermediate Level using JavaScript, JSON and ColdFusion 7

Pranav Prakash ([email protected])

Page 2: Implementing Ajax In ColdFusion 7

Harbinger Systems

Agenda

• Internet basics• AJAX• JSON• Case Study – Adding ILT Classes• Best Practices• Q-n-A

Page 3: Implementing Ajax In ColdFusion 7

Harbinger Systems

The Internet

• The Internet• Connection less in nature

o Server has no idea from where the data is coming

o It just creates a ‘response’ in answer to a ‘request’

Page 4: Implementing Ajax In ColdFusion 7

Harbinger Systems

Under the hood

• How a web page is viewed ?o Client (Firefox) sends a request to server

(google.com)o Server generates a response (generally in HTML)o The response is parsed by the cliento Displayed to the user

• Simple and Synchronizedo One time comm between Client & Servero If there is any new request, the page is reloaded/

new page comes up

Page 5: Implementing Ajax In ColdFusion 7

Harbinger Systems

Limitations

• One time comm. between client and server

• The rendered page is statico No matter if the page is generated by

Static HTML content Dynamically by ColdFusion, Python or PHP

• If anything on the page has to be changed on the fly – no way

Page 6: Implementing Ajax In ColdFusion 7

Harbinger Systems

Agenda

• Internet basics • AJAX• JSON• Performance• Case Study – Adding ILT Classes• Best Practices• Q-n-A

Page 7: Implementing Ajax In ColdFusion 7

Harbinger Systems

AJAX

• AJAX = Asynchronous JavaScript and XML

• AJAX is not a technology in itself, rather a group of technologies

• Constituent technologieso JavaScripto DOMo XML/JSON and of-course HTTPo CSS

Page 8: Implementing Ajax In ColdFusion 7

Harbinger Systems

AJAX in two slides … #1

Page 9: Implementing Ajax In ColdFusion 7

Harbinger Systems

AJAX in two slides … #2

Page 10: Implementing Ajax In ColdFusion 7

Harbinger Systems

AJAX flow

• Make HTTP requesto Creation of XMLHttpRequesto Sending data to servero Callback

• Handling Server responseo onreadystatechange

• Doing something meaningful

Page 11: Implementing Ajax In ColdFusion 7

Harbinger Systems

XMLHttpRequest (XHR)

• Whato DOM API

• Whereo Used inside JavaScript

• Whyo Send HTTP request directly to web servero Load server response directly in JavaScripto Server response can be – XML or plain text

Page 12: Implementing Ajax In ColdFusion 7

Harbinger Systems

Creating XMLHttpRequest

// create ajaxObject supports all browser with XMLHttpRequest Support ajaxObject = function() { try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}catch (e){// Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch (e){try{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}catch (e){alert("Your browser does not support AJAX!");return false;}}}return xmlHttp;} ajax = new ajaxObject();

Page 13: Implementing Ajax In ColdFusion 7

Harbinger Systems

Sending data to server

• Data to web server can be send in many wayso GETo POSTo HEADo Any other

• Everything is supported

Page 14: Implementing Ajax In ColdFusion 7

Harbinger Systems

Sending data to server

• Two methods provided in XMLHttpRequest object for sending datao open()o send()

• Used to send any kind of data to the server

Page 15: Implementing Ajax In ColdFusion 7

Harbinger Systems

XMLHttpRequest open() method

open(method, url, async, user, password)• Opens a new connection• Five parameters

o The HTTP method – GET, POSTo The URL of page being requestedo Sets if the request is Asynchronous. This is the “A”

in AJAX If TRUE, the execution of the JavaScript function will

continue while the response of the server has not yet arrived

o Optional username/password information

Page 16: Implementing Ajax In ColdFusion 7

Harbinger Systems

XMLHttpRequest send() method

send(data)• Initiates the request• Data is optional (not strictly)

o Must use null if no data is to be providedo To be send, only in case of POST-ing the

requesto Should be in form of a query string like name=value&anothername=othervalue&so=on

Page 17: Implementing Ajax In ColdFusion 7

Harbinger Systems

Handling Server Response

• onreadystatechange attribute is used to store the JavaScript function that handles the response from server

• httpRequest.onreadystatechange =

nameOfTheFunction;• What this function should do

o Check the state of requesto Check the status code of server responseo Obtain data and play

Page 18: Implementing Ajax In ColdFusion 7

Harbinger Systems

Checking the state of request

• Checks the current progress of request made• Attribute readyState stores the information• Possible values

o 0 – un initializedo 1 – Loading o 2 – Loaded o 3 – Interactive o 4 – Complete

Page 19: Implementing Ajax In ColdFusion 7

Harbinger Systems

Checking the state of request …

if (httpRequest.readyState == 4) {// everything is good, the response is received } else { // still not ready }

Page 20: Implementing Ajax In ColdFusion 7

Harbinger Systems

Checking the server response code

• There are many server response codes• We are interested in

o 200 ( Good, go ahead)o 404 ( Not found, debugging purposes)o 500 ( Internal Server Error, debugging)o 503 ( Service Not available)

Page 21: Implementing Ajax In ColdFusion 7

Harbinger Systems

Checking the server response code

if (httpRequest.readyState == 4) { if (httpRequest.status == 200) { // perfect! }else {// there was a problem with the request, // maybe a 404 or 500 // show user friendly message}}

Page 22: Implementing Ajax In ColdFusion 7

Harbinger Systems

Obtaining Data

• XMLHttpRequest has two attributes to store data send from server

• responseText o The server response as a string of text

• responseXMLo The server response as a XMLDocument

objecto Can be traversed using JavaScript DOM

functions

Page 23: Implementing Ajax In ColdFusion 7

Harbinger Systems

Summing it all … Algorithm

1.Create an instance of XMLHttpRequest2.If created proceed to #33.Use onreadystatechange to call a function

upon completion4.Open the connection and send the request5.Excellent example at -

https://developer.mozilla.org/en/AJAX/Getting_Started

Page 24: Implementing Ajax In ColdFusion 7

Harbinger Systems

Done with AJAX

• Internet basics• AJAX• JSON• Case Study – Adding ILT Classes• Best Practices• Q-n-A

Page 25: Implementing Ajax In ColdFusion 7

Harbinger Systems

JSON

• JSON = Jason (Phonetically)• JavaScript Object Notation• Lightweight computer data interchange

format• Used as an alternate to XML in web

communication• Text based, simple data structures

Page 26: Implementing Ajax In ColdFusion 7

Harbinger Systems

JSON data types

• Number (integer, real, or floating point)• String (double-quoted Unicode with backslash

escaping)• Boolean (true and false) • Array (an ordered sequence of values, comma-

separated and enclosed in square brackets)• Object (collection of key:value pairs, comma-

separated and enclosed in curly braces)• Null

Page 27: Implementing Ajax In ColdFusion 7

Harbinger Systems

Example JSON

{ "Unassigned_Instructors": [{"name":"Chavan swapnil","id":133693},{"name":"Instructor Default","id" :4},{"name":"prakash Pranav","id":133699},{"name":"s m","id":133700}],"Unassigned_Equipment":[{"name" :"equipment 1","id":3}],"Classrooms": [{"capacity":25,"name":"Test Classroom","id":1},{"capacity":50,"name" :"test classroom (50)","id":2},{"capacity":2,"name":"Test class","id":3},{"capacity":15,"name":"Dev Classroom 1","id":6}],"Assigned_Equipment":[],"Assigned_Instructors":[]}

Page 28: Implementing Ajax In ColdFusion 7

Harbinger Systems

Recreating JSON Object

• The server response is in Text/XML format

• After obtaining the prev text, we need to convert it into JSON Object

• Use of eval()var myClass = eval("(" + class_details + ")");

Page 29: Implementing Ajax In ColdFusion 7

Harbinger Systems

Using the JSON Objects

• myClass.Unassigned_Instructorso Is an array containing the class details

• myClass.Unassigned_Instructors[0].nameo Stores the name of first class

• myClass.Unassigned_Instructors[0].ido Stores the ID corresponding to the class

• myClass. Classroomso Stores an array of class room details

• And so on …

Page 30: Implementing Ajax In ColdFusion 7

Harbinger Systems

Creating JSON in ColdFusion

• Third Party Component named “json.cfc”• Available at

http://www.epiphantastic.com/cfjson/downloads.php

• Create regular Structure, Arrays in Coldfusion and use “JSON.CFC” to convert them into JSON data

Page 31: Implementing Ajax In ColdFusion 7

Harbinger Systems

Creating JSON in ColdFusion…

<cfquery name=“instructors” datasource=“#application.LMSDSN#”><!---// find out instructors ---•</cfquery>

<cfset ResultStruct = StructNew() ><cfset ResultStruct["Assigned_Instructors"] = structnew() >

<cfloop from="1" to ="#instructors2.recordcount#" index="i"><cfset ResultStruct.unassigned_Instructors[i]["id"] = #instructors2.userid[i]# ><cfset ResultStruct.unassigned_Instructors[i]["name"] = #instructors2.lastname[i]# & ' ' & #instructors2.firstname[i]# ></cfloop>

<cfinvoke component="JSON" method="encode" data="#ResultStruct#" returnvariable="result" />

Page 32: Implementing Ajax In ColdFusion 7

Harbinger Systems

Done with JSON

• Internet basics• AJAX• JSON• Case Study – Adding ILT Classes• Q-n-A

Page 33: Implementing Ajax In ColdFusion 7

Harbinger Systems

Adding ILT classes

• Specific to 43x and 44x clients• When Add class page loads

o It initialize lot of instructor, classroom, equipment related data in javascript

o Works great for small amount of datao Also, helps in quick addition of classo Better resource management

Page 34: Implementing Ajax In ColdFusion 7

Harbinger Systems

The B I G picture

• For SOM431, there are 1300 courses, over 50 locations and 97,853 Instructor associations

• When the page loads, over 1000,000 javascript variables were being defined

• Result – latency, browser crashes and frustration, and of course server load

Page 35: Implementing Ajax In ColdFusion 7

Harbinger Systems

The solution

• AJAX• Do not load any course, location,

instructor and equipment details when the page is called

• Let user select something• Use AJAX and fetch details on the fly• Result – Faster page load, less server

burden

Page 36: Implementing Ajax In ColdFusion 7

Harbinger Systems

Homework

• Have a look at following SOM431 files to see how changes have been madeo dsp_class.cfmo act_Saveclass.cfmo getDetails.cfmo Fbx_switch.cfm

• Dir – x:\SOM431\html\training\classscheduler\admin

Page 37: Implementing Ajax In ColdFusion 7

Harbinger Systems

Further resources

• https://developer.mozilla.org/en/AJAX• http://www.json.org/• http://www.epiphantastic.com/cfjson/• http://www.google.com

Page 38: Implementing Ajax In ColdFusion 7

Harbinger Systems

That’s all from my side

Thanks …