52
WEB 2.0 Programming WEB 2.0 Programming with AJAX with AJAX E.Soundararajan E.Soundararajan SIRD, IGCAR SIRD, IGCAR

WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Embed Size (px)

Citation preview

Page 1: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

WEB 2.0 Programming with WEB 2.0 Programming with AJAXAJAX

E.SoundararajanE.Soundararajan

SIRD, IGCARSIRD, IGCAR

Page 2: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Web 2.0 Fly ByWeb 2.0 Fly ByWeb 2.0 is really an “after-the-fact” catch-all for a collectively

recognized phenomena

the foaf project

Page 3: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR
Page 4: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Web 2.0 is the network as platform, spanning all connected devices; Web 2.0 applications are those that make the most of the intrinsic advantages of that platform: delivering software as a continually-updated service that gets better the more people use it, consuming and remixing data from multiple sources, including individual users, while providing their own data and services in a form that allows remixing by others, creating network effects through an "architecture of participation," and going beyond the page metaphor of Web 1.0 to deliver rich user experiences.

Tim O'Reilly, “Web 2.0: Compact Definition?”

Page 5: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Lets continue looking...

Page 6: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR
Page 7: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR
Page 8: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• Personalized

• User oriented

• Easy to Use

• Get you to the information you want

• Useful

What Makes the Web 2.0 Different?

Page 9: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• “Click, wait, and refresh” user interaction

> Page refreshes from the server needed for all events, data submissions, and navigation

> The user has to wait for the response

• Synchronous “request/response” communication model

• Browser always initiates the request

Characteristics of ConventionalWeb Application

Page 10: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• Slow response• Loss of operation context during refresh• Excessive server load and bandwidth consumption• Lack of two-way, real-time communication capabilityfor server initiated updates

These are the reasons why Rich Internet Application(RIA) technologies were born.

Issues of ConventionalWeb Application

Page 11: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• Macromedia Flash

• Java Web Start

• DHTML

• DHTML with IFrame

• AJAX

Rich Internet Application (RIA)Technologies

Page 12: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• Designed for playing interactive movies• Programmed with ActionScript• Implementation examples> Macromedia Flex> Laszlo suite (open source)• Pros:> Good for vector graphics• Cons:> Browser needs a Flash plug-in> ActionScript is proprietary and hard to debug

Macromedia Flash

Page 13: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• Desktop application delivered over the net• Pros> Desktop experience once loaded> Leverages Java technology to its fullest extent> Disconnected operation possible> Application can be digitally signed• Cons> Old JRE-based system do not work

Java Web Start

Page 14: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• DHTML = JavaScript + DOM + CSS

• Used for creating interactive applications

• No asynchronous communication, however

> Full page refresh still required

DHTML (Dynamic HTML)

Page 15: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

IntroductionIntroduction AJAX = Asynchronous JavaScript and XMLAJAX = Asynchronous JavaScript and XML AJAX is not a new programming language, but a technique for AJAX is not a new programming language, but a technique for

creating better, faster, and more interactive web applications.creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with With AJAX, your JavaScript can communicate directly with

the server, using the JavaScript the server, using the JavaScript XMLHttpRequestXMLHttpRequest object. object. With this object, your JavaScript can trade data with a web With this object, your JavaScript can trade data with a web server, without reloading the page.server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages between the browser and the web server, allowing web pages to request small bits of information from the server instead of to request small bits of information from the server instead of whole pages.whole pages.

The AJAX technique makes Internet applications smaller, The AJAX technique makes Internet applications smaller, faster and more user-friendly.faster and more user-friendly.

Page 16: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

About AJAXAbout AJAX AJAX is Based on Web StandardsAJAX is Based on Web Standards AJAX is based on the following web standards:AJAX is based on the following web standards: JavaScriptJavaScript XMLXML HTMLHTML CSSCSS DOMDOM The web standards used in AJAX are well defined, The web standards used in AJAX are well defined,

and supported by all major browsers. AJAX and supported by all major browsers. AJAX applications are browser and platform independent.applications are browser and platform independent.

Page 17: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

DOM (Document Object Model)DOM (Document Object Model) Object Oriented Representation for XML and Object Oriented Representation for XML and

HTML documentsHTML documents

Based on Hierarchical (Tree) StructureBased on Hierarchical (Tree) Structure

allows programs and scripts to build documents, allows programs and scripts to build documents, navigate their structure, add, modify or delete navigate their structure, add, modify or delete elements and contentelements and content

Provides a foundation for developing Provides a foundation for developing querying, filtering, querying, filtering, transformation, rendering etc. transformation, rendering etc.

applications on top of DOM implementationsapplications on top of DOM implementations

Page 18: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

CSS (Cascading Style Sheets)CSS (Cascading Style Sheets)

Set of Formatting rules that tell the browser Set of Formatting rules that tell the browser how to present the documenthow to present the document

Helps to separate the content from the Helps to separate the content from the presentationpresentation

Reduce the download time by removing the Reduce the download time by removing the formatting information from the documentformatting information from the document

More control over formatting than HTMLMore control over formatting than HTML

Page 19: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

So why is AJAX so hot—NOW?So why is AJAX so hot—NOW? Demand for richer applications is growingDemand for richer applications is growing

Broadband means we can—and want to—do moreBroadband means we can—and want to—do more

Recent Google applications have sparked people’s imaginationRecent Google applications have sparked people’s imagination Google gmail, Google suggests, Google gmail, Google suggests, Google MapsGoogle Maps

People are thinking of building APPLICATIONS…not just People are thinking of building APPLICATIONS…not just sitessites

The Tipping PointThe Tipping Point All of this has made rich internet apps reach its tipping point—where All of this has made rich internet apps reach its tipping point—where

adoption spreads rapidly and dramaticallyadoption spreads rapidly and dramatically

Page 20: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

• Google maps > http://maps.google.com/ • Goolgle Suggest > http://www.google.com/webhp?complete=1&hl=en • Gmail > http://gmail.com/ • ZUGGEST- an XMLHttp Experiment using

Amazon > http://www.francisshanahan.com/zuggest.aspx

Real-Life Examples of AJAX apps

Page 21: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

AJAX BasicsAJAX Basics

AJAX Uses HTTP RequestsAJAX Uses HTTP Requests With AJAX, your JavaScript communicates directly With AJAX, your JavaScript communicates directly

with the server, through the JavaScript with the server, through the JavaScript XMLHttpRequestXMLHttpRequest object object

With an HTTP request, a web page can make a With an HTTP request, a web page can make a request to, and get a response from a web server - request to, and get a response from a web server - without reloading the page. The user will stay on the without reloading the page. The user will stay on the same page, and he or she will not notice that scripts same page, and he or she will not notice that scripts request pages, or send data to a server in the request pages, or send data to a server in the background.background.

Page 22: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

AJAX BasicsAJAX Basics The XMLHttpRequest ObjectThe XMLHttpRequest Object By using the XMLHttpRequest object, a web developer By using the XMLHttpRequest object, a web developer

can update a page with data from the server after the page can update a page with data from the server after the page has loaded!has loaded!

AJAX was made popular in 2005 by Google (with Google AJAX was made popular in 2005 by Google (with Google Suggest).Suggest).

Google Suggest is using the XMLHttpRequest object to create Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.server and the server returns a list of suggestions.

The XMLHttpRequest object is supported in Internet Explorer The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7.7.

Page 23: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

A New Way of Building ApplicationsA New Way of Building Applications AJAX Applications Are:AJAX Applications Are:

3-tier client/server apps3-tier client/server apps Browser Browser ↔ ↔ App Server App Server ↔ ↔ Data SourceData Source

Event drivenEvent driven User clicks, user drags, user changes dataUser clicks, user drags, user changes data

Graphics IntensiveGraphics Intensive Visual Effects, Rich Visual ControlsVisual Effects, Rich Visual Controls

Are Data OrientedAre Data Oriented Users are manipulating and entering dataUsers are manipulating and entering data

Are ComplexAre Complex Pages hold many more controls and data than page-oriented Pages hold many more controls and data than page-oriented

applicationsapplications Multiple Master-Detail Relationships in one pageMultiple Master-Detail Relationships in one page

Page 24: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

AJAX will change web developmentAJAX will change web developmentAJAX represents a AJAX represents a fundamental shiftfundamental shift in how in how

web web applicationsapplications are built are built

We’ll be building We’ll be building 3-Tier Client/Server3-Tier Client/Server applications with AJAXapplications with AJAX

Users want enhanced, interactive functionalityUsers want enhanced, interactive functionality They want their data easily accessible and maintainableThey want their data easily accessible and maintainable They don’t want screen flickerThey don’t want screen flicker They don’t want over-the-top GUI—just functionalThey don’t want over-the-top GUI—just functional Once they see an AJAX application—they want it nowOnce they see an AJAX application—they want it now

Page 25: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR
Page 26: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR
Page 27: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Two ways of talking to the Two ways of talking to the server…server…

XMLHTTPRequest objectXMLHTTPRequest object Allows for asynchronous GETs + POSTs to the serverAllows for asynchronous GETs + POSTs to the server Does not show the user anything—no status messagesDoes not show the user anything—no status messages Can have multiple XMLHTTPRequest active at one timeCan have multiple XMLHTTPRequest active at one time Allows you to specify a handler method for state changesAllows you to specify a handler method for state changes Handler notified when request is:Handler notified when request is:

InitializedInitialized StartedStarted In the process of being returnedIn the process of being returned Completely finishedCompletely finished

Originally only available for Microsoft IEOriginally only available for Microsoft IE

Page 28: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

XMLHttpRequest Object: XMLHttpRequest Object: MethodsMethods

open(“method”, “URL”)open(“method”, “URL”) open(“method”, “URL”, async, username, password)open(“method”, “URL”, async, username, password)

Assigns destination URL, method, etc.Assigns destination URL, method, etc. send(content)send(content)

Sends request including postable string or DOM object dataSends request including postable string or DOM object data abort()abort()

Terminates current requestTerminates current request getAllResponseHeaders()getAllResponseHeaders()

Returns headers (labels + values) as a stringReturns headers (labels + values) as a string getResponseHeader(“header”)getResponseHeader(“header”)

Returns value of a given headerReturns value of a given header setRequestHeader(“label”,”value”)setRequestHeader(“label”,”value”)

Sets Request Headers before sendingSets Request Headers before sending

Page 29: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Security IssuesSecurity Issues

You can only hit the domain that the original web You can only hit the domain that the original web page came frompage came from

Because of this, the AJAX technique cannot normally Because of this, the AJAX technique cannot normally be used to access a Web Service of a 3be used to access a Web Service of a 3rdrd party server party server You can wrap those requests through your own serverYou can wrap those requests through your own server You can allow XMLHTTPRequest to access specific sites You can allow XMLHTTPRequest to access specific sites

in your browser security settingsin your browser security settings

IFRAME can be used to access any site if neededIFRAME can be used to access any site if needed

Page 30: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Wow..I didn’tknow soccer

teams did web programming..

Page 31: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

AJAX FrameworksAJAX Frameworks Pure JavaScript FrameworkPure JavaScript Framework

InfrastructureInfrastructure Provides basic piping & portable browser abstractionsProvides basic piping & portable browser abstractions Content up to developerContent up to developer Typical Functionality:Typical Functionality:

Wrapper around XMLHttpRequestWrapper around XMLHttpRequest XML manipulation & interrogationXML manipulation & interrogation DOM manipulations based on responses from XMLHttpRequestDOM manipulations based on responses from XMLHttpRequest

Application FrameworkApplication Framework Includes basic Infrastruture functionalityIncludes basic Infrastruture functionality

Server-Side FrameworkServer-Side Framework HTML/JavaScript GenerationHTML/JavaScript Generation

Server provides complete HTML/JS code generation and browser Server provides complete HTML/JS code generation and browser server server coordinationcoordination

Browser-side coding is for customizationBrowser-side coding is for customization Remote InvocationRemote Invocation

JavaScript calls routed directly to server-side functions (Java Methods) and returned JavaScript calls routed directly to server-side functions (Java Methods) and returned back to Javascript callback handlersback to Javascript callback handlers

Page 32: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Pure JavaScriptPure JavaScript DOJO (9/04)DOJO (9/04) Prototype (2001)Prototype (2001) Open Rico (5/05)Open Rico (5/05) Qooxdoo (5/05)Qooxdoo (5/05)

Pure JavaScript InfrastructuralPure JavaScript Infrastructural AjaxJS (5/05)AjaxJS (5/05) HTMLHttpRequest (2001)HTMLHttpRequest (2001) Interactive Website Framework (5/05)Interactive Website Framework (5/05) LibXMLHttpRequest (6/03)LibXMLHttpRequest (6/03) RSLiteRSLite Sack (5/05)Sack (5/05) Sarissa (2/03)Sarissa (2/03) XHConn (4/05)XHConn (4/05)

Server-Side (Multi Language)Server-Side (Multi Language) Cross-Platform Asynchronous Interface Toolkit (5/05)Cross-Platform Asynchronous Interface Toolkit (5/05) SAJAX (3/05)SAJAX (3/05) Javascript Object Notation (JSON) & JSON-RPCJavascript Object Notation (JSON) & JSON-RPC Javascript Remote Scripting (2000)Javascript Remote Scripting (2000)

Server-Side (Java)Server-Side (Java) Echo2 (3/05)Echo2 (3/05) Direct Web Remoting (DWR) (2005)]Direct Web Remoting (DWR) (2005)] ThinkCAP Minerva (04/2005)ThinkCAP Minerva (04/2005)

Server-Side (Lisp)Server-Side (Lisp) CL-AjaxCL-Ajax

Server-Side (.NET)Server-Side (.NET) Ajax.NET (305)Ajax.NET (305)

Server-Side (PHP)Server-Side (PHP) AjaxAC (4/05)AjaxAC (4/05) JPSpanJPSpan XAJAXXAJAX

Server-Side (Ruby)Server-Side (Ruby) Ruby-On-Rails (3/05)Ruby-On-Rails (3/05)

Pick aFramework…any Framework

www.ajaxpatterns.org

Page 33: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Common WidgetsCommon Widgets Form ValidationForm Validation Interactive GridsInteractive Grids Drilldowns TreeViewsDrilldowns TreeViews Auto CompletionAuto Completion Application Status AreaApplication Status Area Progress BarsProgress Bars Dynamic ListsDynamic Lists TabsTabs AJAX’ed PortletsAJAX’ed Portlets Predictive FetchPredictive Fetch

Page 34: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Sites of InterestSites of Interest www.ajaxmatters.comwww.ajaxmatters.com www.ajaxian.comwww.ajaxian.com www.ajaxpatterns.orgwww.ajaxpatterns.org

Foundational LibrariesFoundational Libraries PrototypePrototype script.acul.usscript.acul.us

very OO foundation to manipulate XMLHTTPRequestvery OO foundation to manipulate XMLHTTPRequest lots of visual effects, autocomplete, sliders, controlslots of visual effects, autocomplete, sliders, controls Core of “Ruby on Rails” AJAX implementationCore of “Ruby on Rails” AJAX implementation

OpenRicoOpenRico Builds on Prototype, adds some controlsBuilds on Prototype, adds some controls Accordion, Live GridAccordion, Live Grid

SarissaSarissa Heavy duty XML library for XSLTHeavy duty XML library for XSLT

SAJAX & XAJAXSAJAX & XAJAX PHP libraries with some good ideasPHP libraries with some good ideas Server driven JS creationServer driven JS creation

Page 35: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Basic AJAX ProcessBasic AJAX ProcessJavaScript– Define an object for sending HTTP requests– Initiate request

• Get request object• Designate a request handler function

– Supply as onreadystatechange attribute of request• Initiate a GET or POST request• Send data

– Handle response• Wait for readyState of 4 and HTTP status of 200• Extract return text with responseText or responseXML• Do something with result

• HTML– Loads JavaScript– Designates control that initiates request– Gives ids to input elements that will be read by script

Page 36: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Define ObjectDefine Object

var request;var request;function getRequestObject() function getRequestObject() {{if (window.ActiveXObject) {if (window.ActiveXObject) {return(new ActiveXObject("Microsoft.XMLHTTP"));return(new ActiveXObject("Microsoft.XMLHTTP"));} else if (window.XMLHttpRequest) {} else if (window.XMLHttpRequest) {return(new XMLHttpRequest());return(new XMLHttpRequest());} else {} else {return(null);return(null);}}}}

Page 37: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Initiate RequestInitiate Request

function sendRequest() {function sendRequest() {

request = getRequestObject();request = getRequestObject();

request.onreadystatechange = handleResponse;request.onreadystatechange = handleResponse;

request.open("GET", "message-data.html", true);request.open("GET", "message-data.html", true);

request.send(null);request.send(null);

}}

Page 38: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Handling ResponseHandling Response

function handleResponse() function handleResponse()

{{

if (request.readyState == 4) {if (request.readyState == 4) {

alert(request.responseText);alert(request.responseText);

}}

}}

Page 39: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

HTML CodeHTML Code<!DOCTYPE html PUBLIC "..."<!DOCTYPE html PUBLIC "...""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Ajax: Simple Message</title><head><title>Ajax: Simple Message</title><script src="mesg.js"<script src="mesg.js"type="text/javascript"></script>type="text/javascript"></script></head></head><body><body><center><center><table border="1" bgcolor="gray"><table border="1" bgcolor="gray"><tr><th><big>Ajax: Simple Message</big></th></tr><tr><th><big>Ajax: Simple Message</big></th></tr></table></table><p/><p/><form action="#"><form action="#"><input type="button" value="Show Message"<input type="button" value="Show Message"onclick="sendRequest()"/>onclick="sendRequest()"/></form></form></center></body></html></center></body></html>

Page 40: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

AJAX DB ExampleAJAX DB Example

Page 41: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

HTML FileHTML File<html><html><head><head><script src="select_name.js"></script><script src="select_name.js"></script></head><body><form> </head><body><form> Select a State:Select a State:<select name="cities" onchange="showCityname(this.value)"><select name="cities" onchange="showCityname(this.value)"><option value="Tamilnadu">Tamilnadu<option value="Tamilnadu">Tamilnadu<option value="Kerala ">Kerala<option value="Kerala ">Kerala<option value="Karnataka">Karnataka <option value="Karnataka">Karnataka </select></select></form><p></form><p><div id="txtHint"><b>City Names will be listed here.</b></div><div id="txtHint"><b>City Names will be listed here.</b></div></p></p>

</body></body></html></html>

Java Script File

JavaScript Function Call

Page 42: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

var xmlHttpvar xmlHttp

function showCityname(str)function showCityname(str){ { xmlHttp=GetXmlHttpObject();xmlHttp=GetXmlHttpObject();if (xmlHttp==null)if (xmlHttp==null) {{ alert ("Your browser does not support AJAX!");alert ("Your browser does not support AJAX!"); return;return; } } var url="http://10.1.6.32/ajax/getname.php";var url="http://10.1.6.32/ajax/getname.php";url=url+"?q="+str;url=url+"?q="+str;url=url+"&sid="+Math.random();url=url+"&sid="+Math.random();xmlHttp.onreadystatechange=stateChanged;xmlHttp.onreadystatechange=stateChanged;xmlHttp.open("GET",url,true);xmlHttp.open("GET",url,true);xmlHttp.send(null);xmlHttp.send(null);}}

Java Script File – Show Cityname() Function

Page 43: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

AJAX - Sending a Request to the ServerAJAX - Sending a Request to the Server

To send off a request to the server, we use the open() To send off a request to the server, we use the open() method and the send() method.method and the send() method.

The open() method takes three arguments. The first The open() method takes three arguments. The first argument defines which method to use when sending argument defines which method to use when sending the request (GET or POST). The second argument the request (GET or POST). The second argument specifies the URL of the server-side script. The third specifies the URL of the server-side script. The third argument specifies that the request should be handled argument specifies that the request should be handled asynchronously. The send() method sends the request asynchronously. The send() method sends the request off to the server. If we assume that the HTML and off to the server. If we assume that the HTML and PHP file are in the same directory, the code would be: PHP file are in the same directory, the code would be:

xmlHttp.open("GET",“getname.php",true); xmlHttp.open("GET",“getname.php",true); xmlHttp.send(null);xmlHttp.send(null);

Page 44: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Defines the url (filename) to send to the server Defines the url (filename) to send to the server Adds a parameter (q) to the url with the content of the Adds a parameter (q) to the url with the content of the

input field input field Adds a random number to prevent the server from Adds a random number to prevent the server from

using a cached file using a cached file Creates an XMLHTTP object, and tells the object to Creates an XMLHTTP object, and tells the object to

execute a function called stateChanged when a execute a function called stateChanged when a change is triggered change is triggered

Opens the XMLHTTP object with the given url. Opens the XMLHTTP object with the given url. Sends an HTTP request to the server Sends an HTTP request to the server

Page 45: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Javascript- State ChangedJavascript- State Changed

function stateChanged() function stateChanged() { { if (xmlHttp.readyState==4)if (xmlHttp.readyState==4){ {

document.getElementById("txtHint").innerHTML=xmlHttp.redocument.getElementById("txtHint").innerHTML=xmlHttp.responseText;sponseText;

}}}}

Page 46: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

State changed FunctionState changed Function

The readyState property holds the status of the The readyState property holds the status of the server's response. Each time the readyState server's response. Each time the readyState changes, the onreadystatechange function will changes, the onreadystatechange function will be executed.be executed.

Request is not initialized -0Request is not initialized -0 The request has been set up – 1The request has been set up – 1 The request has been sent - 2The request has been sent - 2 The request is in process – 3The request is in process – 3 The request is complete - 4The request is complete - 4

Page 47: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

function GetXmlHttpObject()function GetXmlHttpObject(){{var xmlHttp=null;var xmlHttp=null;trytry {{ // Firefox, Opera 8.0+, Safari// Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest();xmlHttp=new XMLHttpRequest(); }}catch (e)catch (e) {{ // Internet Explorer// Internet Explorer trytry {{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }} catch (e)catch (e) {{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }} }}return xmlHttp;return xmlHttp;}}

JavaScript – Define XmlHttpObject

Page 48: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

XMLHttpRequest PropertiesXMLHttpRequest Properties onreadystatechangeonreadystatechange

Event handler that fires at each state changeEvent handler that fires at each state change You implement your own function that handles thisYou implement your own function that handles this

readyState – current status of requestreadyState – current status of request 0 = uninitialized0 = uninitialized 1 = loading1 = loading 2 = loaded2 = loaded 3 = interactive (some data has been returned)3 = interactive (some data has been returned)

This is broken in IE right nowThis is broken in IE right now 4 = complete4 = complete

statusstatus HTTP Status returned from server: 200 = OKHTTP Status returned from server: 200 = OK

responseTextresponseText String version of data returned from serverString version of data returned from server

responseXMLresponseXML XML DOM document of data returnedXML DOM document of data returned

statusTextstatusText Status text returned from serverStatus text returned from server

Page 49: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

<?php<?phpheader("Cache-Control: no-cache, must-revalidate");header("Cache-Control: no-cache, must-revalidate"); // Date in the past// Date in the pastheader("Expires: Mon, 26 Jul 1997 05:00:00 GMT");header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

$q=$_GET["q"];//lookup all hints from array if length of q>0$q=$_GET["q"];//lookup all hints from array if length of q>0$query = " select city from city where state = '$q' ";$query = " select city from city where state = '$q' ";$mysql_link=mysql_connect("10.1.6.32","guest","");$mysql_link=mysql_connect("10.1.6.32","guest","");mysql_select_db("test",$mysql_link);mysql_select_db("test",$mysql_link);$mysql_result = mysql_query($query, $mysql_link);$mysql_result = mysql_query($query, $mysql_link);$response= "<table>";$response= "<table>";while ( $row = mysql_fetch_row($mysql_result)) while ( $row = mysql_fetch_row($mysql_result)) { { $city = $row[0]; $city = $row[0]; $response.="<tr><td><b>".$city."</b></td></tr>"; $response.="<tr><td><b>".$city."</b></td></tr>"; }}$response.="</table>";$response.="</table>";echo $response;echo $response;?>?>

PHP Code – Server Script

Page 50: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

– Dojo.• Open source JavaScript toolkit with Ajax support• http://www.dojotoolkit.org/– Google Web Toolkit• Write code in Java, translate it to JavaScript• http://code.google.com/webtoolkit/– script.aculo.us• Free JavaScript toolkit with Ajax support• http://script.aculo.us/– Yahoo User Interface Library (YUI)• Free JavaScript toolkit with some Ajax support• http://developer.yahoo.com/yui/

Client-Side Tools

Page 51: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

– Direct Web Remoting• Lets you call Java methods semi-directly from JavaScript• http://getahead.ltd.uk/dwr/– JSON/JSON-RPC• For sending data to/from JavaScript with less parsing• http://www.json.org/• http://json-rpc.org/– JSP custom tag libraries• Create tags that generate into HTML and JavaScript• http://courses.coreservlets.com/Course-Materials/msajsp.html84 J2EE training: http://courses.coreservlets.com

Server-Side Tools

Page 52: WEB 2.0 Programming with AJAX E.Soundararajan SIRD, IGCAR

Questions?Questions?