Implementing Ajax In ColdFusion 7
-
Upload
pranav-prakash -
Category
Technology
-
view
1.513 -
download
1
description
Transcript of 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])
Harbinger Systems
Agenda
• Internet basics• AJAX• JSON• Case Study – Adding ILT Classes• Best Practices• Q-n-A
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’
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
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
Harbinger Systems
Agenda
• Internet basics • AJAX• JSON• Performance• Case Study – Adding ILT Classes• Best Practices• Q-n-A
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
Harbinger Systems
AJAX in two slides … #1
Harbinger Systems
AJAX in two slides … #2
Harbinger Systems
AJAX flow
• Make HTTP requesto Creation of XMLHttpRequesto Sending data to servero Callback
• Handling Server responseo onreadystatechange
• Doing something meaningful
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
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();
Harbinger Systems
Sending data to server
• Data to web server can be send in many wayso GETo POSTo HEADo Any other
• Everything is supported
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
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
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
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
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
Harbinger Systems
Checking the state of request …
if (httpRequest.readyState == 4) {// everything is good, the response is received } else { // still not ready }
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)
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}}
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
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
Harbinger Systems
Done with AJAX
• Internet basics• AJAX• JSON• Case Study – Adding ILT Classes• Best Practices• Q-n-A
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
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
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":[]}
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 + ")");
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 …
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
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" />
Harbinger Systems
Done with JSON
• Internet basics• AJAX• JSON• Case Study – Adding ILT Classes• Q-n-A
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
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
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
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
Harbinger Systems
Further resources
• https://developer.mozilla.org/en/AJAX• http://www.json.org/• http://www.epiphantastic.com/cfjson/• http://www.google.com
Harbinger Systems
That’s all from my side
Thanks …