welcome to web 2.0 an ajax presentation carlos fernando scheidecker antunes [email protected]...

42
Welcome to WEB 2.0 Welcome to WEB 2.0 An AJAX presentation An AJAX presentation Carlos Fernando Scheidecker Carlos Fernando Scheidecker Antunes Antunes [email protected] [email protected] http://www.cs.utah.edu/~antunes/AJ http://www.cs.utah.edu/~antunes/AJ AX AX Updated Feb 8 2006

Post on 15-Jan-2016

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Welcome to WEB 2.0Welcome to WEB 2.0

An AJAX presentationAn AJAX presentation

Carlos Fernando Scheidecker AntunesCarlos Fernando Scheidecker [email protected]@cs.utah.edu

http://www.cs.utah.edu/~antunes/AJAXhttp://www.cs.utah.edu/~antunes/AJAX

Updated Feb 8 2006

Page 2: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

What is WEB 2.0?What is WEB 2.0?

• Web 2.0 is a term often applied to a perceived ongoing transition of the World Wide Web from a collection of websites to a full-fledged computing platform serving web applications to end users. Ultimately Web 2.0 services are expected to replace desktop computing applications for many purposes.

Page 3: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

What is AJAX ?What is AJAX ?

Page 4: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

What is AJAX ?What is AJAX ?

• Ajax (Asynchronous Javascript And XML) allows to navigate web pages while the page itself - quietly and unobtrusively - sends requests to the server for more data, and can use that data to update the user interface without the user having to wait for a new page or a page refresh.

Page 5: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

What is AJAX ?What is AJAX ?

• What this means in practice is that we can build interfaces to our web applications which are much more like those our users are used to from their desktop applications. Forms, text boxes and images can be populated automatically with data retrieved from the server, data grids can be sorted or paginated, and server-side databases can be queried and edited - all without the user having to wait for pages to load.

Page 6: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

How does AJAX work?How does AJAX work?

• Ajax may be thought of as a 'buffer layer' between the user and the server. When the user gives instructions to the web page (for instance by clicking a button or link) the message is sent not directly to the server, but to our Ajax 'engine'.

• This engine, when it needs to, makes requests of the server. But these requests may not necessarily correspond one-to-one with the user's requests. Sometimes Ajax will have foreseen the user's requirement and will already have the information requested. This is the 'Asynchronous' bit.

• And guess what? Our page talks to the Ajax engine using Javascript commands embedded in the source code of the page, taking care of the second letter of Ajax.

• There are several means by which the server can send data back to the Ajax engine - and as you've probably guessed by now, one of the most useful is XML.

Page 7: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

How does AJAX work?How does AJAX work?

Page 8: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Why use AJAX ?Why use AJAX ?

• Provides a rich client interface• Allows for background processing, the

asynchronous process• Saves bandwidth reducing costs• Saves time, only chunks of information are sent

over the wire• Increases speed of the application• Better overall result• Allows for features that are not possible with the

standard web system programming paradigm

Page 9: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Defining principles of AJAXDefining principles of AJAX

• The browser hosts an application, not just content

• The server delivers data, not content

• User interaction with the application can be fluid and continuous

• Real coding which requires discipline

Page 10: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Key elements of AJAXKey elements of AJAX

• JavaScript

• Cascading Style Sheets

• Document Object Model (DOM)

• XMLHttpRequest object

Page 11: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

JavaScriptJavaScript

• Allows programmatic interface with many of the browser’s inbuilt capabilities.

• Provides events and function calls

• JavaScript is the GLUE for an AJAX application.AJAX applications ARE NOT written in JavaScript although the existing books claim so.

AJAX IS NOT JAVASCRIPT

Page 12: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

CSSCSS

• It is a way of defining reusable visual styles for web page elements.

• In an AJAX application CSS is a powerful tool because it provides capabilities to modify the user interface on the fly, redrawing parts of the page. i.e.: you can make a button, a list an component appear or disappear.

Page 13: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

CSS exampleCSS example

• You can embed CSS within a HTML document, or an external file which allows for better coding and maintenance.

• Example of a CSS style property:

.coolstyle {font-size: 14pt;font-family: courier new, courier, monospace;font-weight: bold;color: gray;

}

Page 14: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Where to place your CSSWhere to place your CSS

• Embedding CSS in a html page. Put it on top of the page source within the <head></head> tags.

Example:<head><title>Ajax is cool</title><style type=text/css>.style19 { color: #000099 }</style></head>

Page 15: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Where to place your CSSWhere to place your CSS

• Put it on a separate file and include it from your html page.To include CSS on your page just add the following between the <head></head> tags.<head><LINK REL=StyleSheet HREF="basics.css" TITLE="Contemporary">

</head>

• The basics.css file is just a text file with the css code as in the previous slide. The file can include more than one style.

Page 16: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Useful CSS exampleUseful CSS example

• I’ve actually used this style on a working project as part of an implementation à la Google Suggest.

.tablestyle { color: blue; overflow: visible; float: auto; height: auto; width: auto; background-color: yellow; position:absolute; clip:rect(0px 300px 300px 0px)}

<img src="images/logo.jpg“ onmouseover="javascript:printTable('t1')" onmouseout="javascript:hideTable('t1')“>

<span class="tablestyle" id="t1">

• Then, all I had to do was to use JavaScript to make it appear and disappear

function printTable(aId) { id = aId; getTable(); tableObject(id,timeTexto);}

function tableObject(id,content) { this.displayed = null; document.getElementById(id).innerHTML =

content;}

function hideTable(aId) { id = aId;document.getElementById(aId).innerHTML = ‘ ';}

Page 17: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

DOM DOM Document Object ModelDocument Object Model

• DOM exposes a document (a.k.a. web page) to the JavaScript engine.

• Using DOM, the structure of a web page, can be manipulated programmatically.

• HTML tags are organized in a tree structure. A good way to understand that is comparing it to a OOP language.

Page 18: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

DOM DOM Document Object ModelDocument Object Model

Page 19: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

DOM DOM Document Object ModelDocument Object Model

Page 20: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

DOM DOM Document Object ModelDocument Object Model

Page 21: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

DOM DOM Document Object ModelDocument Object Model

• Every node in a DOM is a child, grandchild and so on of document.

• Every element of a HTML page can be tagged with an unique id which helps to reference and manipulate it.

• Examples:<p id=‘hello’><div id=‘empty’></div>

Page 22: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

DOM DOM Document Object ModelDocument Object Model

• Getting a programmatic reference to a specific node ID in one function call:

Var hellopar = document.getElementById(‘hello’);

• Changing the content of a node in one function call:

document.getElementById(‘empty’).innerHTML=‘<br>’;

Page 23: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

• The XMLHTTPRequest object is JavaScript's device for communicating with the server 'in the background' (i.e. without the necessity of a page load or refresh) and forms the nucleus of the 'Ajax' application model.

• Before we can use such an object, however, it must be created. How this is done depends on which browser we are using, so we need some code to either detect the browser type and perform the relevant action, or test all of the means of creating the XMLHTTPRequest object until we find one that works.

Page 24: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

• Example of how to create an XMLHttpRequestObject: if (window.XMLHttpRequest) { // Non-IE browsers

req = new XMLHttpRequest();

} else if (window.ActiveXObject) { // IE

req = new ActiveXObject("Microsoft.XMLHTTP");

}

• Here I am testing before creating the object. This is how I usually code my AJAX apps.

Page 25: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

• Another way to create an XMLHttpRequestObject: try { req = new XMLHttpRequest(); /* e.g. Firefox */} catch(e) {

try { req = new ActiveXObject(\"Msxml2.XMLHTTP\"); /*some

versions IE */ } catch (e) {

try { req = new ActiveXObject("Microsoft.XMLHTTP"); /* some

versions IE */ } catch (E) { req = false; } } }

And Here I am trying to create a XMLHttpRequest object until it works.

Page 26: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

• Methods of the XMLHttpRequestObject:

• There a few methods that the XMLHttpRequestObject offers, however the 2 most used ones are open() and send()

• Open() is used to connect to the server.Example: http.open(“GET”, “http://www.antunes.eti.br/test.php”, true); The third argument, when set to True, determines that the request will be executed asynchronously, when the send() method is called.

• Send() is used to transmit the request to the server. You can include a post string or a DOM object argument.Example: http.send(null); or http.send(); for IE (practical experience)

Page 27: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

• Properties of the XMLHttpRequestObject.

There are four properties of a XMLHttpRequestObject and they are essential for an AJAX application. They are:

• onReadyStateChange

• readyState

• responseText

• responseXML

Page 28: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

• onReadyStateChange defines an event handler which executes every time the readyState property of the object changes

• readyState can take integer values of zero to four: 0 = uninitialized, 1 = loading, 2 = loaded, 3 = interactive, 4 = complete. In general, we are only interested in a readyState of 4 (complete) which tells us that the server request has completed and we can therefore use the data which has been returned

Page 29: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

• responseText

refer to the information returned from the server in text format, for instance an HTML chunk.

• responseXML

refer to the information returned from the server, in XML format.

Page 30: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObjectProperty Description

onReadyStateChange Event handler which is fired at every event change. (http event)

readyState Here are the possible status:0 – uninitialized1 – loading2 – loaded3 – interactive4 – complete (we’ll focus on this one)

responseText Data returned from server in String form

responseXML Data returned from server in XML form. DOM compatible

status These are the HTTP status codes such as 200, 404, 500 etc.

statusText This is a string message which is associated with its respective HTTP status code.

Page 31: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

XMLHttpRequestObjectXMLHttpRequestObject

Method Description

Abort() Stops the current request

getAllResponseHeaders Return all headers name and value as a string

getResponseHeader(“<name>”) Returns the value of the given Header

Open(“method”,”URL”,[true,false]) Opens a connection and retrieves a response from the URL passed.

send(content) Transmits request

setRequestHeader(“name”,“value”) Assigns value to an specific header.

Page 32: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

An event handlerAn event handler

• In order to call an XMLHttpRequest we need an event.

This event is called from the page. For example, a button that is clicked or any kind of JavaScript event that can make a function call.

Here’s an example of a JavaScript event that calls a function updateData(param).

<form name="rssForm">  <select name="rssFeed" onChange=“updateData(this.value);">    <option value=""></option>    <option value="cnn_rss.xml">CNN Top Stories</option>    <option value="slashdot_rss.xml">Slashdot</option>    <option value="dans_rss.xml">Dan's Data</option> </select></form>

Page 33: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

An event handlerAn event handler

• When the event is fired, the function updateData(param) is called:

function updateData(param) {  var myurl = “http://www.antunes.eti.br/test.php”;

•  http.open("GET", myurl + "?id=" + escape(param), true);  http.onreadystatechange = processStateChange; // event handler   http.send(null);

•}

This function assumes that a XMLHttpRequestObject was created and it is called http. What happens next?

Page 34: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

An event handlerAn event handler

• The updateData function listens to changes on the XMLHttpRequest object and every time there is a state change caught by the event onReadyStateChange, a function called processStateChange is called.

http.onreadystatechange = useHttpResponse;

• function processStateChange() { if (http.readyState == 4) { // Complete if (http.status == 200) { // OK response document.getElementById(id).innerHTML = http.responseText; } else { alert("Problem: " + http.statusText); } } }

Page 35: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Sample applicationSample application

• The following is a very simple Hello world! Application in AJAX to illustrate what we have seen so far. We will start with the html part of it.

• <html>• <head>• <title>Hello world!</title>• <script language="JavaScript" type="text/JavaScript"

scr"js/hello.js">• </script>• </head>

• <body onLoad="retrieveURL('http://www.antunes.eti.br/helloWorld.php');">

• <h1>Example</h1>

• Hello world!.<hr>

• This example shows how a piece of this document can be built and displayed on-the-fly.

• <br>

• <span id="theResult"></span>

• <br>• </body>

• </html>

Page 36: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Sample applicationSample application

• When the document loads, the onLoad event is fired which calls the function retrieveURL passing the URL of the CGI as the param. After the asynchronous call is performed, we can update the page using DOM by changing the innerHTML property of the “theResult” node.

Page 37: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Sample applicationSample application• This is the hello.js JavaScript code:

• var req; // global XMLHttpRequest object•

• function retrieveURL(url) {

• if (window.XMLHttpRequest) { // Non-IE browsers

• req = new XMLHttpRequest();

• req.onreadystatechange = processStateChange;

• try {

• req.open("GET", url, true);

• } catch (e) {

• alert(e);

• }

• req.send(null);

• }

• else if (window.ActiveXObject) { // IE

• req = new ActiveXObject("Microsoft.XMLHTTP");

• if (req) {

• req.onreadystatechange = processStateChange;

• req.open("GET", url, true);

• req.send();

• }

• }

• }

• function processStateChange() {

• if (req.readyState == 4) { // Complete

• if (req.status == 200) { // OK response

• document.getElementById("theResult").innerHTML = req.responseText;

• } else {

• alert("Problem: " + req.statusText);

• }

• }

• }

Page 38: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

AJAX FrameworksAJAX Frameworks

• As you can see, there are quite a few steps on implementing an Ajax application. As you start to code Ajax you will realize that you are repeatedly performing same tasks such as:

- Support Multiple Browsers- Create the XMLHttpRequest- Handling events

• Naturally, you will organize your code into libraries so that you can make better use of common functionality.

• Ajax is new and as such it is quite dynamic as its frameworks are made to be.

• Frameworks exist to make mere mortals life easier.

• Real programmers might not like them

Page 39: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

AJAX FrameworksAJAX Frameworks

• Here’s a list of frameworks:

- DOJO - dojotoolkit.org- Rico – openrico.org/home.page- qooxdo – qooxdo.oss.sclund.de- Tibet – www.technicalpursuit.com- Google AJAXSLT - goog-ajaxslt.sourceforge.net- libXmlRequest – www.whitefrost.com/index.jsp- RSLite – www.ashleyit.com/rs/rslite/- SACK – twilightuniverse.com/projects/sack/- Sarrisa – sarissa.sourceforge.net/doc- XHConn – xkr.us/code/javascript/XHConn/

Page 40: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

What’s next?What’s next?

• Next time we will:

• Show working Ajax applications and walk the code step by step.

• The examples will include:- Hello application- Google Suggest XML example- Dynamic CSS tables- A database grid- Dynamic select boxes à la eBay- Cache buster techniques

• CGI tips• Formats: HTML,XML and JSON

Page 41: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

QuestionsQuestions

Have any questions, concerns or fears?

This is the time.

Page 42: Welcome to WEB 2.0 An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu antunes/AJAX antunes@cs.utah.edu

Thank you!Thank you!

Please remember:

I will keep the material, examples and source code on the following address:

http://www.cs.utah.edu/~antunes/AJAX/

[email protected]