420 likes | 550 Views
Welcome to WEB 2.0. An AJAX presentation Carlos Fernando Scheidecker Antunes antunes@cs.utah.edu http://www.cs.utah.edu/~antunes/AJAX. Updated Feb 8 2006. What is WEB 2.0?.
E N D
Welcome to WEB 2.0 An AJAX presentationCarlos Fernando Scheidecker Antunesantunes@cs.utah.eduhttp://www.cs.utah.edu/~antunes/AJAX Updated Feb 8 2006
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. antunes@cs.utah.edu
What is AJAX ? antunes@cs.utah.edu
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. antunes@cs.utah.edu
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. antunes@cs.utah.edu
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. antunes@cs.utah.edu
How does AJAX work? antunes@cs.utah.edu
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 sentover the wire • Increases speed of the application • Better overall result • Allows for features that are not possible with the standard web system programming paradigm antunes@cs.utah.edu
Defining 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 antunes@cs.utah.edu
Key elements of AJAX • JavaScript • Cascading Style Sheets • Document Object Model (DOM) • XMLHttpRequest object antunes@cs.utah.edu
JavaScript • 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 antunes@cs.utah.edu
CSS • 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. antunes@cs.utah.edu
CSS 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;} antunes@cs.utah.edu
Where 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> antunes@cs.utah.edu
Where 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. antunes@cs.utah.edu
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 = ‘ '; } Useful CSS example antunes@cs.utah.edu
DOM Document 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. antunes@cs.utah.edu
DOM Document Object Model antunes@cs.utah.edu
DOM Document Object Model antunes@cs.utah.edu
DOM Document Object Model antunes@cs.utah.edu
DOM Document 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> antunes@cs.utah.edu
DOM Document 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>’; antunes@cs.utah.edu
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. XMLHttpRequestObject antunes@cs.utah.edu
XMLHttpRequestObject • 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. antunes@cs.utah.edu
XMLHttpRequestObject • 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. antunes@cs.utah.edu
XMLHttpRequestObject • 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) antunes@cs.utah.edu
XMLHttpRequestObject • 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 antunes@cs.utah.edu
XMLHttpRequestObject • onReadyStateChangedefines an event handler which executes every time the readyState property of the object changes • readyStatecan 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 antunes@cs.utah.edu
XMLHttpRequestObject • 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. antunes@cs.utah.edu
XMLHttpRequestObject antunes@cs.utah.edu
XMLHttpRequestObject antunes@cs.utah.edu
An 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> antunes@cs.utah.edu
An 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? antunes@cs.utah.edu
An 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); } } } antunes@cs.utah.edu
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> Sample application antunes@cs.utah.edu
Sample 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. antunes@cs.utah.edu
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); } } } Sample application antunes@cs.utah.edu
AJAX 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 antunes@cs.utah.edu
AJAX 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/ antunes@cs.utah.edu
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 antunes@cs.utah.edu
Questions Have any questions, concerns or fears?This is the time. antunes@cs.utah.edu
Thank you! Please remember:I will keep the material, examples and source code on the following address: http://www.cs.utah.edu/~antunes/AJAX/ antunes@cs.utah.edu antunes@cs.utah.edu