Your SlideShare is downloading. ×
AJAX and Web 2.0
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

AJAX and Web 2.0


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. 1 AJAX and Web 2.0 INFO 344 Winter 2007 Last time Creating PHP web services with XML Write functions that output XML Consuming web services with PHP Connect using file_get_contents Parse XML with SimpleXML Today Today Dynamic pages with AJAX The AJAX model AJAX is an umbrella term describing a group of technologies JavaScript, XML, others Coined by Jesse James Garrett in 2005 AJAX allows a web page to interact dynamically with the server In AJAX, the browser can reconnect to a web site to fetch data, after the page has loaded Add new data to web page Defining AJAX Asynchronous Javascript and XML Asynchronous: requests occur in the background while the page is loaded Javascript: AJAX in the browser uses JS XML: Data often exchanged between browser and server as XML Why AJAX? Allows us to provide more responsive user interfaces Similar to desktop applications Provide access to rich data Without having to download anything Interact with web services
  • 2. 2 AJAX in action The Heart of AJAX XmlHttpRequest (XHR): a built-in JavaScript library that allows the browser to make a connection to a web server Fetch data without reloading the page Retrieves data as plain text or XML Similar to file_get_contents in PHP Supported by all major browsers IE, Mozilla/Firefox, Safari, Opera, etc. Static page model AJAX Writing AJAX Two parts to writing an AJAX application Server-side (in PHP) Write web service functions Return values or objects (as XML) Client-side (JavaScript) Use the XmlHttpRequest object to call web service Parse XML values Update page content using DOM On the server side Write web service functions as we have previously Return objects in an appropriate format
  • 3. 3 Returning XML Our web service needs to indicate that it's returning an XML document Web server assumes it's outputting HTML PHP didn't care, but JS more sensitive Needed for AJAX XML parsing Add a "content-type" header at the top of any PHP page that returns an XML document header("Content-type: text/xml"); XML web service <?php header("Content-type: text/xml"); // get the user's name $name = $_REQUEST["name"]; // output "hello, name!" as XML echo "<response>Hello, $name!</response>"; ?> On the client side When we wish to perform an AJAX request, we perform the following steps 1. Define a function to handle the server response 2. Write a function to initiate the AJAX request 3. Attach the request to a link or button The request is asynchronous; when the server responds, the function is called 1. Parses server response 2. Updates page Client-side concerns All major browsers support XmlHttpRequest However! Different browsers support XHR differently In Mozilla, built-in In IE6, embedded ActiveX control, etc Different methods to instantiate Solution: Use a JavaScript library that provides automatic cross-browser code We'll use a library called Prototype Using prototype.js Prototype is a library that provides a number of features to make AJAX programming easy We'll only use the basics, but it's worth checking out Include prototype.js in your HTML file <script type="text/javascript" src="prototype.js"></script> Use separate script tags for your scripts! Use the Ajax.Request object to call the server Pass the object a handler function Function will be called in the background Handler function runs when the server returns Javascript/HTML skeleton <html> <head> <title>title</title> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> function sendAjaxRequest(args) { … } function handleAjaxResponse(response) { … } </script> </head> <body> <input type="button" value="Go" onclick="sendAjaxRequest(args)"/> </body> </html>
  • 4. 4 Handling the XHR response Define a function to handle the XHR response Function should take one parameter, response function addTwoResponse(response) { // alert the result of the AJAX call alert(response.responseText); } Calling AJAX.Request Create the AJAX.Request object Pass it the URL and the name of the handling function function sendAJAXRequest() { var url = " ML.php"; url += "?a=5"; url += "&b=10"; var ajax = new Ajax.Request(url, {onComplete: addTwoResponse }); } Parsing result values When the AJAX request returns, the onComplete function executes Passed the response object, which contains two important properties responseText – the text of the server response responseXML – the server response as an XML DOM tree Which we use depends on the kind of data our web service sends out Web service output format Web service can return a number of formats Plain text – use responseText normally Easy for single values, bad for complex data XML – use responseXML, use DOM tree Useful, but unwieldy Must use clunky JS XML tools HTML – use responseText, add directly to document Easy to handle, but code separation issues Scenario addTwo web service adds two numbers Web page calls service with parameters 10 and 4 Data can be returned in several formats Handled differently depending on format Handling plain text Web service returns "14" function addTwoResponse(response) { // alert the result of the AJAX call alert(response.responseText); }
  • 5. 5 Handling XML Returns <response> <first>4</first> <second>14</second> <operation>plus</operation> <result>18</result> </response> Unfortunately, no SimpleXML for JS We have to use the DOM to access XML document.getElementById(id) document.getElementsByTagName(tag) Parsing the XML We can access the XML values using document.getElementsByTagName Walk through XML; big mess Example: to get value of first "result" field, use document.getElementsByTagName("result")[0] deValue We can write a function to make this easier // retrieve the nth element with the specified name function getValue(element, name, index) { return element.getElementsByTagName(name)[index]. firstChild.nodeValue; } XML example Use getValue to handle the XML function addTwoResponse(response) { // get the XML object var xml = response.responseXML; // get the value of the "result" attribute var sum = getValue(xml, "result", 0); alert("Sum is " + sum); } One more thing: method success Sometimes web service functions may succeed or fail depending on some condition Username and password correct/incorrect in login script Our web service can pass a success or failure message in the XML response Respond appropriately Success or failure Success message <response> <message>OK</message> <first>4</first> <second>14</second> <operation>plus</operation> <result>18</result> </response> Failure message <response> <message>Error: invalid arguments</message> </response> Handling error cases function addTwoResponseWithError(response) { // get the XML object var xml = response.responseXML; // check for error message if (getValue(xml, "message", 0) != "OK") { // output error message alert(getValue(xml, "message", 0)); } else { // no error // get the value of the "result" attribute var sum = getValue(xml, "result", 0); alert("Sum is " + sum); } }
  • 6. 6 AJAX limitations Server restrictions: browser can only access services on the same server as original page e.g. page on can't access service on Can be overcome with a proxy that routes from one server to another Usability and accessibility restrictions: Technology not fully supported by all browsers Older browsers, mobile browsers Voice and other alternative browsers Pages should fall back on non-AJAX method This is still a major problem Now you try it Write an AJAX version of your web service lab from Tuesday Instead of two pages, one page Page makes AJAX call Adds service response to page Briefly: Web 2.0 What is Web 2.0? Some people have been using the term Web 2.0 to describe the "next generation" of web applications Name originally comes from the name of a marketing-related conference Has been adopted by designers, users, bloggers, business people AJAX is part of Web 2.0 Who is Web 2.0? Web 2.0 buzz Web 2.0 isn't a thing… it's a state of mind. –Andy Budd Ajax, democracy, and not dissing users. –Paul Graham Web 2.0 is a marketing concept used by venture capitalists and conference promoters to try to call another bubble into existence. –Dave Winer Simply put, Web 2.0 is a perceived transition of the web to web applications. Web 2.0 is the next generation of technology solutions where interactive content is the norm. –Sharon Housley Web 2.0 is all about remixing, not about designing. The best metaphor for web 2.0 is the DJ, not the composer. Web 2.0 is a product of remix culture. – Jonathan Boutelle Web 2.0 is giving up control. It is setting the data free. – DeWitt Clinton
  • 7. 7 O'Reilly's definition 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. Technology of Web 2.0 Rich, responsive Web applications Use AJAX to make web apps like desktop apps Open architecture for sharing data Web APIs Allow systems to be combined via "mashups" Standards-based design Valid XHTML, CSS Web 2.0 as social movement Focus on social connections Social networking and community building Sharing bookmarks, photos, videos Get users to do work for you Tagging systems User-produced content Is Web 2.0 a fad? Definitely! But the idea of Web 2.0 is shaping the design of web applications Some interesting ideas behind the hype