23
Web 2.0 Web 2.0 technologies: Ajax Prof. Filippo Lanubile Outline What is Ajax Differences between Ajax and classic web apps Core technologies How Ajax works Ajax frameworks Prof. Filippo Lanubile Ajax frameworks Pros and Cons Alternatives to Ajax

Microsoft PowerPoint - Ajax [modalità compatibilità]

Tags:

Embed Size (px)

Citation preview

Page 1: Microsoft PowerPoint - Ajax [modalità compatibilità]

Web 2.0

Web 2.0 technologies: Ajax

Prof. Filippo Lanubile

Outline

• What is Ajax• Differences between Ajax and classic web apps• Core technologies• How Ajax works• Ajax frameworks

Prof. Filippo Lanubile

Ajax frameworks• Pros and Cons• Alternatives to Ajax

Page 2: Microsoft PowerPoint - Ajax [modalità compatibilità]

What is Ajax? (1)

Prof. Filippo Lanubile

What is Ajax? (2)

Asynchronous JavaScript and XML• A web development technique for improving the

interactivity of web applications• Key features

– Make requests to the server and get responses

Prof. Filippo Lanubile

without reloading the entire page – Requests do not lock up the web application until

responses come back

Page 3: Microsoft PowerPoint - Ajax [modalità compatibilità]

What is Ajax? (3)

Ajax is part of Web 2.0• Second generation of

web applications• Web 2.0 gives users an

experience closer to desktop applications

Prof. Filippo Lanubile

p pp• Web 2.0 apps

encourage collaboration and participation– Blogs, wikis, folksonomies

Differences between Ajax and classic web apps browser client

user interfaceClassic web application

Ajax application

browser client

user interface

HTML+CSS data

HTTP request

HTTP(S) transport

user interface

Ajax engine

JavaScript call

HTTP request

HTTP(S) transport

HTML+CSS data

Classic web application

Prof. Filippo Lanubileserver-side systems

web server

datastores, backendprocessing, legacy systems

server-side systems

web server

datastores, backendprocessing, legacy systems

XML data

Source: Adaptive Path

Page 4: Microsoft PowerPoint - Ajax [modalità compatibilità]

Prof. Filippo LanubileClassic search engine

Prof. Filippo LanubileAjax search engine

Page 5: Microsoft PowerPoint - Ajax [modalità compatibilità]

Prof. Filippo LanubileClassic web mail

Prof. Filippo LanubileAjax web mail

Page 6: Microsoft PowerPoint - Ajax [modalità compatibilità]

Prof. Filippo LanubileClassic mapping site

Prof. Filippo LanubileAjax mapping site

Page 7: Microsoft PowerPoint - Ajax [modalità compatibilità]

Core technologiesAjax is a group of technologies bundled togetherAjax is a group of technologies bundled together • HTML and CSS

– for presenting• XML

– for transferring data between the web server and browser• DOM (Document Object Model)

– to access elements within the web page and the xml file read on the web server

Prof. Filippo Lanubile

on the web server• JavaScript

– to dynamically display and interact with the information presented

• XMLHttpRequest object – to exchange data asynchronously with the web server

XMLHttpRequest object: Attributeschanges from 0 to 4

readyStatestatusresponseTextresponseXmlonreadystatechange

XMLHttpRequest

changes from 0 to 4 0: Unitialized. 1: Open. 2: Sent. 3: Receiving. 4: Loaded.

Status code in HTTP Reply200 ok … 404 page not found

holds the entity body of the HTTP

Prof. Filippo Lanubile

open(in method, in uri, in async)send(in data)setRequestHeader(in header, in value)

y greply as a string of characters

holds the entity body of the HTTP reply as a xml parsed document

holds the callback function that handles the HTTP reply

Page 8: Microsoft PowerPoint - Ajax [modalità compatibilità]

XMLHttpRequest object: Methods

Create a connectionmethod: type of HTTP request

(GET or POST)uri: the location of the resource async: true (default) / false

Send a request to the server

Prof. Filippo Lanubile

Se d a equest to t e se edata: the entity body of the HTTP request (null for a GET request)

Sets to value the header of the HTTP request (useful for MIME types)

Create a new XMLHttpRequest object

<script language="javascript“ type="text/javascript">

var request = new XMLHttpRequest();

</script>

Prof. Filippo Lanubile

Page 9: Microsoft PowerPoint - Ajax [modalità compatibilità]

Add support for Microsoft browsers <script language="javascript" type="text/javascript">var request = false;var request = false;try {request = new XMLHttpRequest();

} catch (trymicrosoft) {try {request = new ActiveXObject("Msxml2.XMLHTTP");

} catch (othermicrosoft) {try {request = new ActiveXObject("Microsoft.XMLHTTP");

} catch (failed) {

Prof. Filippo Lanubile

} ( ) {request = false;

}}

}if (!request)alert("Error initializing XMLHttpRequest!");

</script>

Ajax in Action

• Sample 1: Break Neck Pizza• Sample 2: Boards 'R' Us report

– XMLHttpRequest with responseText• Sample 3: Boards 'R' Us report (expanded)

– XMLHttpRequest with responseXml

Prof. Filippo Lanubile

Page 10: Microsoft PowerPoint - Ajax [modalità compatibilità]

How Ajax Works• Basics in

– HTML and CSS– XML– DOM– JavaScript– PHP– XMLHttpRequest

• Sample 1: Break Neck Pizza– XMLHttpRequest with

responseText• Sample 2: Boards 'R' Us

report– XMLHttpRequest with

responseTextS l 3 B d 'R' U

Prof. Filippo Lanubile

• Tools– Browser

• DOM Inspector– Web server

• PHP v5

• Sample 3: Boards 'R' Us report (expanded)– XMLHttpRequest with

responseXml

Make a request

1. Get data you need from the HTML form

2. Build the URL to connect to3. Open a connection to the

web server4. Setup a callback function

Prof. Filippo Lanubile

4. Setup a callback function5. Send the request

Try Break Neck Pizza Source: Head First book

Page 11: Microsoft PowerPoint - Ajax [modalità compatibilità]

Make a request: 1. Get data you need from the HTML form<body onLoad="document.forms[0].reset();">y ()<p><img src="breakneck-logo.gif"

alt="Break Neck Pizza" /></p><form method="POST" action="placeOrder.php"><p>Enter your phone number:<input type="text" size="14“ name="phone" id="phone“

onChange="getCustomerInfo();" /></p><p>Type your order in here:</p><p><textarea name="order" id="order"

/ /

Prof. Filippo Lanubile

rows="6" cols="50"></textarea></p><p>Your order will be delivered to:</p><p><textarea name="address" id="address"

rows="4" cols="50"></textarea></p><p><input type="submit" id="submit"

value="Order Pizza" /></p></form></body></html>

Make a request: 2. Build the URL to connect to

function getCustomerInfo() {

var phone = document.getElementById("phone").value;

var url = "lookupCustomer.php?phone=" +

escape(phone);

...

Prof. Filippo Lanubile

Page 12: Microsoft PowerPoint - Ajax [modalità compatibilità]

Make a request: 3. Open a connection to the web server

function getCustomerInfo() {

var phone = document.getElementById("phone").value;

var url = "lookupCustomer.php?phone=" +

escape(phone);

request.open("GET", url, true);

Prof. Filippo Lanubile

...

Make a request: 4. Setup a callback function

function getCustomerInfo() {

var phone = document.getElementById("phone").value;

var url = "lookupCustomer.php?phone=" +

escape(phone);

request.open("GET", url, true);

request.onreadystatechange = updatePage;

Prof. Filippo Lanubile

...

Page 13: Microsoft PowerPoint - Ajax [modalità compatibilità]

Make a request: 5. Send the request

function getCustomerInfo() {

var phone = document.getElementById("phone").value;

var url = "lookupCustomer.php?phone=" +

escape(phone);

request.open("GET", url, true);

request.onreadystatechange = updatePage;

Prof. Filippo Lanubile

request.send(null);

}

Handle the responsef ti d t P () {function updatePage() {

if (request.readyState == 4) {

if (request.status == 200) {

/* Get the response from the server */

var customerAddress = request.responseText;

/* Update the HTML web form */

document.getElementById("address").value =

Prof. Filippo Lanubile

g y ( )

customerAddress;

} else

alert("Error! Request status is " +

request.status);

}

Page 14: Microsoft PowerPoint - Ajax [modalità compatibilità]

Boards 'R' Us report• A web form that

b it t tsubmits requests to a PHP script

• The PHP script looks up how many boards have been sold

• The PHP script uses the selling price and the unit cost to update

Prof. Filippo Lanubile

profit • The entire page is

reloaded just for two changing numbers

Classic version

Reviewing the Boards ‘R’ Us HTML<html><head><title>Boards 'R' Us</title><link rel="stylesheet" type="text/css" href="boards.css" />

</head>

<body><h1>Boards 'R' Us :: Custom Boards Report</h1><div id="boards"><table><tr><th>Snowboards Sold</th><td><span id="boards-sold">1012</span></td></tr>

<tr><th>What I Sell 'em For</th><td>$<span id="price">249.95</span></td></tr>

<tr><th>What it Costs Me</th>

Prof. Filippo Lanubile

<tr><th>What it Costs Me</th><td>$<span id="cost">84.22</span></td></tr>

</table><h2>Cash for the Slopes: $<span id="cash">167718.76</span></h2>

<form method="GET" action="getUpdatedBoardSales.php"><input value="Show Me the Money" type="submit" />

</form></div>

</body></html>

Page 15: Microsoft PowerPoint - Ajax [modalità compatibilità]

Reviewing the Boards ‘R’ Us PHP script (1)<?php

// Start with an arbitrary number of boards sold$totalSold = 1012;

// Reflect new salessrand((double)microtime() * 1000000);$totalSold = $totalSold + rand(0,1000);$price = 249.95;$cost = 84.22;$cashPerBoard = $price - $cost;$cash = $totalSold * $cashPerBoard;?>

Prof. Filippo Lanubile

?<html><head><title>Boards 'R' Us</title><link rel="stylesheet" type="text/css" href="boards.css" />

</head><body><h1>Boards 'R' Us :: Custom Boards Report</h1>

...

Reviewing the Boards ‘R’ Us PHP script (2)...<div id="boards"><table>

<tr><th>Snowboards Sold</th><td><span id="boards-sold">

<?php print $totalSold; ?></span></td></tr><tr><th>What I Sell 'em For</th><td>$<span id="price">

<?php print $price; ?></span></td></tr><tr><th>What it Costs Me</th><td>$<span id="cost">

<?php print $cost; ?></span></td></tr>

Prof. Filippo Lanubile

</span></td></tr></table><h2>Cash for the Slopes: $<span id="cash">

<?php print $cash; ?></span></h2>

<form method="GET" action="getUpdatedBoardSales.php"><input value="Show Me the Money" type="submit" />

</form></div>

</body></html>

Page 16: Microsoft PowerPoint - Ajax [modalità compatibilità]

Use Ajax to fix the web report

1. Create a new object to make requests to the server– createRequest()

2. Write a JavaScript function to request new board sales totals– getBoardsSold()

Prof. Filippo Lanubile

getBoardsSold()3. Update report with new numbers using

JavaScript– updatePage()

Ajax version

1. Create a new object to make requests to the server<html><head><title>Boards 'R' Us</title><link rel="stylesheet" type="text/css" href="boards.css" /><script type="text/javascript" src="text-utils.js"> </script><script language="javascript" type="text/javascript">var request = null;function createRequest() {

try {request = new XMLHttpRequest();

} catch (trymicrosoft) {try {

request = new ActiveXObject("Msxml2.XMLHTTP");} catch (othermicrosoft) {

try {

Prof. Filippo Lanubile

try {request = new ActiveXObject("Microsoft.XMLHTTP");

} catch (failed) {request = null;

}}

}

if (request == null)alert("Error creating request object!");

}

Page 17: Microsoft PowerPoint - Ajax [modalità compatibilità]

2. Write a JavaScript function to request new board sales totals

function getBoardsSold() {createRequest();var url "getUpdatedBoardSales ajax php";var url = "getUpdatedBoardSales-ajax.php";request.open("GET", url, true);request.onreadystatechange = updatePage;request.send(null);

}

<?php// Start with an arbitrary number of boards sold$totalSold = 1012;// Reflect new sales

The new PHP script

Prof. Filippo Lanubile

srand((double)microtime() * 1000000);$totalSold = $totalSold + rand(0,1000);echo $totalSold;?>

<form method="GET"><input value="Show Me the Money" type="button"

onClick="getBoardsSold();" />

The new HTML form

3. Update report with new numbers using JavaScriptfunction updatePage() {

if ( t d St t 4) {if (request.readyState == 4) {var newTotal = request.responseText;var boardsSoldEl = document.getElementById("boards-sold");var cashEl = document.getElementById("cash");replaceText(boardsSoldEl, newTotal);

/* Figure out how much cash Katie has made */var priceEl = document.getElementById("price");var price = getText(priceEl);var costEl = document.getElementById("cost");var cost = getText(costEl);

hP B d i t

Prof. Filippo Lanubile

var cashPerBoard = price - cost;var cash = cashPerBoard * newTotal;

/* Update the cash for the slopes on the form */cash = Math.round(cash * 100) / 100;replaceText(cashEl, cash);

}

Page 18: Microsoft PowerPoint - Ajax [modalità compatibilità]

Boards 'R' Us report (expanded)• This time there are• This time there are

three numbers coming from the server-side script– Snowboards sold– Boot sold– Bindings sold

Prof. Filippo LanubileAjax version

Revisiting Boards ‘R’ Us HTML (1)<html><html><head><title>Boards 'R' Us</title><link rel="stylesheet" type="text/css" href="boards.css“ /><script type="text/javascript" src="ajax.js"> </script><script type="text/javascript" src="text-utils.js"> </script><script type="text/javascript" src="boards.js"> </script>

</head><body><h1>Boards 'R' Us :: How Much Butt We're Kicking</h1><div id="boards"><table><tr><th>Snowboards Sold</th>

Prof. Filippo Lanubile

<tr><th>Snowboards Sold</th><td><span id="boards-sold">1672</span></td></tr>

<tr><th>What I Sell 'em For</th><td>$<span id="boards-price">249.95</span></td></tr>

<tr><th>What it Costs Me</th><td>$<span id="boards-cost">84.22</span></td></tr>

</table>...

Page 19: Microsoft PowerPoint - Ajax [modalità compatibilità]

Revisiting Boards ‘R’ Us HTML (2)...

<table><tr><th>Boots Sold</th><td><span id="boots-sold">312</span></td></tr>

<tr><th>What I Sell 'em For</th><td>$<span id="boots-price">175.47</span></td></tr>

<tr><th>What it Costs Me</th><td>$<span id="boots-cost">54.23</span></td></tr>

</table><table><tr><th>Bindings Sold</th><td><span id="bindings-sold">82</span></td></tr>

<tr><th>What I Sell 'em For</th><td>$<span id="bindings-price">146.92</span></td></tr>

<tr><th>What it Costs Me</th>

Prof. Filippo Lanubile

<tr><th>What it Costs Me</th><td>$<span id="bindings-cost">98.03</span></td></tr>

</table><h2>Cash for the Slopes: $<span id="cash">318936.42</span></h2>

<form method="GET"><input value="Show Me the Money" type="button"

onClick="getNewTotals();" /> </form>

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

Revisiting Boards ‘R’ Us PHP script<?php

// Start with an arbitrary number of sales$bootsSold = 1672;$boardsSold = 312;$bindingsSold = 82;

// Reflect new salessrand((double)microtime() * 1000000);$bootsSold = $bootsSold + rand(0,10);$boardsSold = $boardsSold + rand(0,5);$bindingsSold = $bindingsSold + rand(0,3);

header("Content-Type: text/xml");

Prof. Filippo Lanubile

header( Content Type: text/xml );echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";?>

<totals><boards-sold><? echo $boardsSold; ?></boards-sold><boots-sold><? echo $bootsSold; ?></boots-sold><bindings-sold><? echo $bindingsSold; ?></bindings-sold></totals>

Page 20: Microsoft PowerPoint - Ajax [modalità compatibilità]

XML as a string XML as a tree of nodes

<?xml version="1.0" encoding="UTF-8"?><totals>

<boards-sold>1672</boards-sold><boots-sold>312</boots-sold><bindings-sold>82</bindings-sold>

</totals>

totals

boards-sold

1672

boots-sold

312

Prof. Filippo Lanubile

Node

Parent

Prev. Sibling Next Sibling

First Child Last Child

312

bindings-sold

82

Using responseXML in the JavaScript function (1)function updatePage() {if (request readyState == 4) {if (request.readyState 4) {

if (request.status == 200) {// Get the updated totals from the XML responsevar xmlDoc = request.responseXML;var xmlBoards = xmlDoc.getElementsByTagName("boards-sold")[0];var totalBoards = xmlBoards.firstChild.nodeValue;var xmlBoots = xmlDoc.getElementsByTagName("boots-sold")[0];var totalBoots = xmlBoots.firstChild.nodeValue;var xmlBindings = xmlDoc.getElementsByTagName("bindings-sold")[0];var totalBindings = xmlBindings.firstChild.nodeValue;

Prof. Filippo Lanubile

// Update the page with new totalsvar boardsSoldEl = document.getElementById("boards-sold");var bootsSoldEl = document.getElementById("boots-sold");var bindingsSoldEl = document.getElementById("bindings-sold");var cashEl = document.getElementById("cash");replaceText(boardsSoldEl, totalBoards);replaceText(bootsSoldEl, totalBoots);replaceText(bindingsSoldEl, totalBindings);

...

Page 21: Microsoft PowerPoint - Ajax [modalità compatibilità]

Using responseXML in the JavaScript function (2)...

// Figure out how much cash Katie has made on boardsb d i l d l d("b d i ")var boardsPriceEl = document.getElementById("boards-price");

var boardsPrice = getText(boardsPriceEl);var boardsCostEl = document.getElementById("boards-cost");var boardsCost = getText(boardsCostEl);var cashPerBoard = boardsPrice - boardsCost;var cash = cashPerBoard * totalBoards;

// Figure out how much cash Katie has made on bootsvar bootsPriceEl = document.getElementById("boots-price");var bootsPrice = getText(bootsPriceEl);var bootsCostEl = document.getElementById("boots-cost");var bootsCost = getText(bootsCostEl);

Prof. Filippo Lanubile

g ( )var cashPerBoot = bootsPrice - bootsCost;var cash = cash + (cashPerBoot * totalBoots);

// Figure out how much cash Katie has made on bindingsvar bindingsPriceEl = document.getElementById("bindings-price");var bindingsPrice = getText(bindingsPriceEl);var bindingsCostEl = document.getElementById("bindings-cost");var bindingsCost = getText(bindingsCostEl);var cashPerBinding = bindingsPrice - bindingsCost;var cash = cash + (cashPerBinding * totalBindings);

...

Using responseXML in the JavaScript function (3)...

// d h h f h l h b f// Update the cash for the slopes on the web formcash = Math.round(cash * 100) / 100;replaceText(cashEl, cash);

} else {var message = request.getResponseHeader("Status");if ((message.length == null) || (message.length <= 0)) {

alert("Error! Request status is " + request.status);} else {

alert(message);}

}}

Prof. Filippo Lanubile

}}

Page 22: Microsoft PowerPoint - Ajax [modalità compatibilità]

Ajax frameworks

Provide all the required functions, server side and client side, for the Ajax engine

• JavaScript-based client-side frameworks– Es. Dojo toolkit

• Server-side frameworks – PHP frameworks

Prof. Filippo Lanubile

• Es. Sajax

– Java frameworks• Es. Google Web Toolkit (GWT)

– .NET frameworks• Es. ASP.Net Ajax

Pros and Cons☺☺• Interactivity

– make web pages feel more responsive to user actions

• Established technologies (no browser plug-in)– HTML, CSS, DOM, XML from

W3C– JavaScript is an

• Broken expected behavior of the browser’s Back button

• Need to deal with different implementations in different browsers and platforms– In MS IE 6, XMLHttpRequest

is an ActiveX– In Mozilla XMLHttpRequest

Prof. Filippo Lanubile

JavaScript is an implementation of ECMAScript, from ECMA

– XMLHttpRequest is now a W3C draft specification

In Mozilla, XMLHttpRequest is a native JavaScript object

• Accessibility– Need to provide fallback

options to comply with WAI accessibility guidelines

Page 23: Microsoft PowerPoint - Ajax [modalità compatibilità]

Alternatives to Ajax for interactive web applications• Adobe

– Flash: browser plugin for playing interactive movies using a compressed vector graphics format

– AIR: runtime engine that executes JavaScript and Flash outside the browser

– Flex: programming environment for creating Flash and AIR applications

• Sun– Applet Java: slow and legacy – Java Web Start: downloadable client out of the browser– JavaFX: scripted apps run inside their containers or on the browser

via pluginvia plugin• Mozilla

– XML User Interface Language (XUL)• Microsoft

– Silverlight: cross-browser, cross.platform, cross-device plugin• supports .NET, JavaScript and XAML (Extensible Application Markup

Language)Prof. Filippo Lanubile

Selected Readings• Original article

– Garrett JJ, “Ajax: A New Approach to Web Applications”, February 2005 http://www.adaptivepath.com/publications/essays/archives/000385.php

IEEE CS• IEEE CS paper– Paulson LD, "Building Rich Web Applications with Ajax," Computer, 38(10), pp.

14-17, October 2005– Lawton, G. 2008. New Ways to Build Rich Internet Applications. Computer 41, 8

(Aug. 2008), 10-12. DOI= http://dx.doi.org/10.1109/MC.2008.302• developerWorks

– Brett McLaughlin, Mastering Ajax -http://www-128.ibm.com/developerworks/views/web/libraryview.jsp?search_by=Mastering+Ajax

• Books– McLaughlin B, Head Rush Ajax,

Prof. Filippo Lanubile

g jO’Reilly, March 2006, 446 pages

• Sample code at Head First Labshttp://www.headfirstlabs.com/books/hrajax/

– Crane D, Pascarello E, James D, Ajax in Action, Manning Pub., October 2005, 680 pages

• Wiki – http://ajaxpatterns.org/• Blog - http://ajaxian.com/