AJAX Workshop Notes

17
Sponsored by Upsilon Pi Epsilon The Computer Science Honors Society XML and AJAX

description

Put on by USC's Upsilon Pi Epsilon as part of Wonderful World of Web2.0 Workshop Series. http://pollux.usc.edu/~upe/

Transcript of AJAX Workshop Notes

Page 1: AJAX Workshop Notes

Sponsored byUpsilon Pi Epsilon

The Computer Science Honors Society

XML and AJAXXML and AJAX

Page 2: AJAX Workshop Notes

XML: Basics

• XML stands for EXtensible Markup Language

• XML is a markup language much like HTML

• XML was designed to describe data

• XML tags are not predefined. You must define your own tags

• XML should use a Document Type Definition (DTD) or an XML Schema to describe the data

• XML is a W3C Recommendation

• HTML is about displaying information, while XML is about describing information.

• XML doesn’t do anything itself- You do something with it.

• Source: http://www.w3schools.com/xml/xml_whatis.asp

Page 3: AJAX Workshop Notes

XML: Syntax & Example

• Tags open and close with <>

• Attributes surrounded by quotation marks

• A string containing special characters may be surrounded by “<![CDATA[ ]>”

• <note type=“urgent”>

• <to>Tove</to>

• <from>Jani</from>

• <heading>Reminder</heading>

• <body>Don't forget me this weekend!</body>

• </note>

Page 4: AJAX Workshop Notes

AJAX: Huh?•Asynchronous JavaScript and XML (AJAX)

•Allows for asynchronous interaction with a web server

•Enables refreshes of only portions of content that the user is interacting with

•Creates a faster, more pleasant user experience

•Arguably the most important part of “Web 2.0”

Page 5: AJAX Workshop Notes

AJAX:

•Cuts down on user wait time

•Uses client to offload some work from the server

•Asynchronous operation

Page 6: AJAX Workshop Notes

AJAX: XMLHTTPRequest

•This object makes the whole thing possible

•Not available in IE (in their defense, they invented the idea and implemented it first)

•use the ActiveX object “Microsoft.XMLHTTP”

•Sends a request to a web server complete with headers and parameters

•Uses callback methods for status changes

Page 7: AJAX Workshop Notes

Step 1) Creating Request

var httpRequest;try { httpRequest = new XMLHttpRequest(); } catch (trymicrosoft) { try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { httpRequest = false; } } }

if (!httpRequest ) alert("Error initializing XMLHttpRequest!");

Page 8: AJAX Workshop Notes

Step 2) Sending Request

function sendRequest() {url="getflickrranking.php?word=dog";

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

httpRequest.onreadystatechange = processRequest;

httpRequest.send(null); }

Page 9: AJAX Workshop Notes

XMLHTTP: MethodsMethod Description

abort()Stops the current request

getAllResponseHeaders()Returns complete set of headers (labels and values) as a string

getResponseHeader("headerLabel")

Returns the string value of a single header label

open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])

Assigns destination URL, method, and other optional attributes of a pending request

send(content)Transmits the request, optionally with postable string or DOM object data

setRequestHeader("label", "value")

Assigns a label/value pair to the header to be sent with a request

Page 10: AJAX Workshop Notes

XMLHTTP: Properties

Property Description

onreadystatechange Event handler for an event that fires at every state change

readyState

Object status integer:0 = uninitialized1 = loading2 = loaded3 = interactive4 = complete

responseText String version of data returned from server process

responseXMLDOM-compatible document object of data returned from server process

statusNumeric code returned by server, such as 404 for "Not Found" or 200 for "OK"

statusText String message accompanying the status code

Page 11: AJAX Workshop Notes

Step 3) Handling Response

function processRequest() {     if (httpRequest.readyState == 4)     {        

if(httpRequest.status == 200)         { //process request here

        }         else         {             alert("Error loading page\n" + httpRequest.status + ":"

+ httpRequest.statusText);        }     }   

}

Page 12: AJAX Workshop Notes

Step 4) Processing Response

// in process request functionvar photo = httpRequest.responseXML.getElementsByTagName("photo")[1];var id = photo.getAttribute("id");var owner = photo.getAttribute("owner");var secret = photo.getAttribute("secret");var server = photo.getAttribute("server");var title = photo.getAttribute("title");

document.getElementById("imgDIV").innerHTML = '<strong>' + title + '</strong>';var img = document.createElement('img');img.setAttribute('src', 'http://static.flickr.com/'+server+'/'+id+'_'+secret+'_m.jpg');document.getElementById("imgDIV").appendChild(img);

Page 13: AJAX Workshop Notes

XML: Useful Methods/Members

• element.childNodes[n]

• element.firstChild

• element.nodeValue()

• element.nodeName()

• element.attributes()

• element.getAttribute(“attributeName”);

• document.getElementsByTagName(“tagName”)

• More: http://developer.mozilla.org/en/docs/Gecko_DOM_Reference

Page 14: AJAX Workshop Notes

AJAX: Challenge #1

•Using skeleton code, make an image search

•Make an input box, have user input word, press search button, send the AJAX request

•When AJAX request returns, update a div below the search box with the image results nicely formatted

•Bonus #1: Show all 5 image results (for loop!) at each different size, nicely formatted

•Bonus #2: Illustrate user-inputted name with images (search for letters on Flickr)

Page 15: AJAX Workshop Notes

AJAX: Design Considerations

• http://ajaxian.com/archives/ajax-experience-day-3-bill-scott-on-ajax-design-patterns-and-principles

• Users don’t always notice sections of the page have updated – consider coloring or somehow marking newly updated parts, especially if small

• Users aren’t used to clicking on a button and having nothing happen – show a loading indicator when the request has been sent, when its done processing, remove it

• (http://www.ajaxload.info/ - generate a custom gif)

• “If you writing a user interface, make sure it responds in 1/10th of a second”

Page 16: AJAX Workshop Notes

Google Gadgets AJAX!

•Google Gadgets has its own asynchronous functions for getting data:

IG_FetchContent(url, func)

IG_FetchXMLContent(url, func)

•Simplifies GET requests for Google Gadgets, eliminates ~12 lines of code

Page 17: AJAX Workshop Notes

Google Gadgets AJAX: Example<?xml version="1.0" encoding="UTF-8" ?> <Module> <ModulePrefs title="Music Mash" height="300" scaling="false" /> <Content type="html"> <script language="javascript" type="text/javascript">

function sendRequest() {url = "getflickrranking.php?word=dog";

_IG_FetchXMLContent(url,processRequest); }

function processRequest() {      if (httpRequest.readyState == 4)     {      

if(httpRequest.status == 200)         {  //process request

        }         else         {             alert("Error loading page\n" + httpRequest.status + ":"

+ httpRequest.statusText);        }     

}   }var newDiv = Document.createElement("div");newDiv.id = "imgDiv";document.body.onload = sendRequest;

</script> ]]> </Content> </Module>