Your SlideShare is downloading. ×
0
DNA of Ajax ApplicationsDesigning and Building Ajax Applications with Patterns                                      Bill W...
Background• Games, research, science, military, biz• Apps, frameworks, widget sets• Developer, designer• Object-oriented b...
Ajax at Yahoo!• Acquisition of Oddpost led to mission to evangelize Ajax goodness throughout Yahoo• Summer 2005 - Ajax Eva...
Yahoo! Pattern Library Release                http://developer.yahoo.net/ypatterns/                     Designing and Buil...
yuiblog.comhttp://yuiblog.com                     Designing and Building with Ajax   5
Yahoo! Patterns Discussion Grouphttp://groups.yahoo.com/group/ydn-patterns/                                              D...
Current Set of Patterns                      Breadcrumbs. Module Tabs. Navigation                      Tabs. Auto Complete...
Rich Design Patterns            Drag and Drop. Drag and Drop Modules. In Page Editing.              In Page Custom Editing...
Y! Patterns as a Platform (Web 2.0)                                                                             Yahoo! ser...
Yahoo! UI Library                          Auto Complete      Tree                                                      Sl...
Richness       Designing and Building with Ajax   11
Defining Richness: Web in 3D• Interaction Dimension                                     Interaction          event• Data D...
Classic Web• Interaction                                                 page course-grained                        Intera...
Classic Web Illustrated                      browser                                   Http    My Profile                  ...
Ajax = Just-in-Time. Immediacy.                                           Just-in-time dataJust-in-time presentation      ...
Ajax Model - New & Improved!• New! Deeper Interaction• Now with Just-in-Time                                   Interaction...
Ajax Illustrated                                         browser    My Profile                                onreadystatec...
AJAX vs Ajax• AJAX = Asynchronous JavaScript and XML• Strict definition is using XMLHttpRequest (XHR) to retrieve  XML wit...
Other Remote Scripting Techniques• Hidden IFrame• <img> src• <script> src hack• CSS href hack• JS to faceless Java applets...
Patterns           Designing and Building with Ajax   20
Rich Design Patterns         Drag and Drop. Drag and Drop Modules. In Page Editing. In         Page Custom Editing. Direct...
Principle. Immediacy. (Give Live Feedback)pattern. Live Suggest.pattern. Auto Complete.                                   ...
Keep the goal in mindDesign for immediacyIs it narrowing or is it distractingUse feedback to boost confidenceLet the user ...
Keep the goal in mindDesign for immediacy                                                          Keep the user engagedIs...
Keep the goal in mindDesign for immediacy                                                          Keep the user engagedIs...
Keep the goal in mindDesign for immediacy                                                                Keep the user eng...
Principle. Directness. (Keep it Direct)                                               pattern. Inline Editing.pattern. Dra...
Prefer interaction within the pageWhat about discoverability?                                     Designing and Building w...
Prefer interaction within the pageWhat about discoverability?                                     Use direct editing on pa...
Prefer interaction within the pageWhat about discoverability?                                     Use direct editing on pa...
1Prefer interaction within the pageWhat about discoverability?                                     Use direct editing on p...
Principle. Invitational. (Offer an Invitation)pattern. Hover Invitation.                                                  ...
Make it engagingUse lightweight events as a welcome matRediscover the hover                                          Desig...
3 Offer an InvitationMake it engagingUse lightweight events as a welcome mat                                              ...
Make it engagingUse lightweight events as a welcome mat                                                                 Ke...
Make it engagingUse lightweight events as a welcome mat                                                                   ...
Principle. In Page Interaction. (Cross Borders Reluctantly)pattern. Endless Scrolling.   pattern. In Context Expand.      ...
Rethink process flowsIts the user’s model, not the page modelEvery page jump is a mental speed bump                       ...
Rethink process flowsIts the user’s model, not the page model                                                             ...
Rethink process flowsIts the user’s model, not the page model                                                             ...
Use overlaysFor momentary interruptionReplace page transitionWhen editing an individual, more complex itemBe symmetricalNo...
Use overlaysFor momentary interruption                                                                  Use in-context exp...
Principle. Light Footprint. (Keep a Light Footprint)                             pattern. Rating an Object.pattern. Rememb...
Watch your click weightKeep actions immediate and lightCount “clicks”                                   Designing and Buil...
Watch your click weightKeep actions immediate and lightCount “clicks”                                       Design for eng...
Watch your click weightKeep actions immediate and lightCount “clicks”                                       Design for eng...
Principle. Cinematic Effects. (Use Transitions)pattern. Fade Transition + Self-Healing Transition.pattern. Slide + Animate...
Speak to the BRAINUnderstanding attention processingSending the wrong message                                     Designin...
Speak to the BRAINUnderstanding attention processing                                              What you can communicate...
Speak to the BRAINUnderstanding attention processing                                              What you can communicate...
Simple observations• The more rapid the change the more important the  event.• Rapid movement is seen as more important th...
Principle. Rich Objects. (Think in Objects)pattern. Shareable Object.                                              Designi...
7 Think in ObjectsRethinking the modelWhat is the user’s mental model?How to distinguish from content?                    ...
7 Think in ObjectsRethinking the modelWhat is the user’s mental model?                                                    ...
7 Think in ObjectsRethinking the modelWhat is the user’s mental model?                                                    ...
So What Can XHR Do?• Make a request• Return a response• And do it asynchronously          response           XHR          ...
Ajax Pattern DNA• Every Ajax design pattern consists of a• Trigger (event or timer)• Operation (ajax)• Update (dom)     Tr...
Trigger• Every pattern of interaction starts with• a user event• a timer event   mouseout hover keypress keydown          ...
OperationFive basic operations define what you can do• Lookup I can get information when I need it• Persist I can save in ...
Operation. LookupI can get information when I need it  Auto Complete. Deferred Content Loading. Dynamic Goal. Narrowing   ...
Lookup live search        Keystroke             Lookup                    Dropdown                     lookup            r...
Lookup endless scrolling  Rico LiveGrid                                     Yahoo! Mail Beta (Oddpost)         Scroll     ...
Operation. PersistI can save in real-time Drag and Drop Modules. In Page Editing. In Page Custom Editing. Direct State Edi...
Persist inline edit           Save                                              New          Button                Persist...
Persist persistent portals          Drop                                             Drop         Module              Pers...
Operation. ValidateI can prevent errors early              per field validate keystroke validate              inline form ...
Operation. InvokeI can make things happen now             fire and forget lightweight action   Trigger              Invoke...
Operation. MessageI can communicate instantly               two-way chat   real-time auction             collaborative whi...
Update  • User interface changes to reflect what is happening       slideout slideover dropdown popup                 ball...
Five Operations Define Ajax• Lookup. I can get information when I need it• Persist. I can save in real-time• Validate. I c...
Steps to Understanding Ajax• Use the patterns• Understand XHR - operations• Understand event management - triggers• Know t...
Pattern-O-Matic Drag &                                    Lightweight Onscroll  Select  Hover                             ...
Ajax 101A Look Under the Hood                        Bill W. Scott, Y! Ajax Evangelist                        b.scott@yaho...
Operation. Using XHR           Designing and Building with Ajax   74
Ajax                                                               XHROperation. Using XHR• The five operations are not bu...
Ajax                                                                                                  XHRSimple Ajax ‘Hell...
Ajax                                                                XHRAjax How To1. Create a request object2. Write a cal...
1. Create a Request Object                                                                    1. Createvar xhr = null;if (...
Ajax                                                                                                     XHRXHR MethodsMet...
Ajax                                                             XHRXHR PropertiesProperty             Descriptiononreadys...
2. Write a Callback                                                                    Ajax                               ...
3. Make the Request                                                                          Ajax                         ...
3. Make the Request - Choosing Between GET and POST                                                                       ...
3. Make the Request: Handling the Request on the Server Side• Its just a normal HTTPRequest • Normal mechanism for getting...
4. Parse the Response                                                                  Ajax                               ...
4. Parse the Response: Formatting an XML Response on the Server                                                           ...
4. Parse the Response: Handling an XML Response on the Client                                                             ...
4. Parse the Response: Xml Document API                                                                                   ...
4. Parse the Response: A little more parsing.<?xml version="1.0" ?><root>   <contents>    This data was brought to you by ...
Handling the Response                                                                       Ajax                          ...
Handling the Response: Server-Side-GUI Method                                                                             ...
Handling the Response: Direct-HTML Method                                                                          Ajax   ...
Handling the Response: View-From-Model Method                                                                             ...
Ajax                                                                  XHRJSON• JavaScript supports several string based no...
JSON Response: Object Literal                                                                      Ajax                   ...
JSON Response: Array Literal                                                                  Ajax                        ...
JSON Response: JSON is JavaScript                                                                       Ajax              ...
JSON Response: Parsing JSON                                                                    Ajax                       ...
JSON Response: Y! JSON API                                                                                  Ajax          ...
Building an Ajax Weather Widget Using an XML Service                        Server                  XHR                   ...
REST Service - weather.com                                                              weather.com exposes               ...
XML Response from weather.com         <?xml version="1.0" encoding="ISO     <cc>         -8859-1"?>                       ...
Rico/Prototype Response<?xml version="1.0" encoding="ISO-8859-1"?><ajax-response>  <response type="element" id="ccInfo">  ...
Simple DIV Structure Defines the Accordion<div id="weather"> <div id="current">   <div id="currentHeader" class="accordion...
The Ajax Code  function registerAjaxStuff() {     ajaxEngine.registerRequest( getWeatherInfo, ajax_weather_info );     aja...
JSON Trip Finder                                  Server               XHR                     Designing and Building with...
REST Service Request - Yahoo! Trip Planner - JSON                                                                    Yahoo...
JSON Response                     {"ResultSet":{"firstResultPosition":                     1,"totalResultsAvailable":"16",...
The Ajax/JSON Code<script>function showResponse() {     if (xhr.readyState == 4) {          if (xhr.status == 200) {      ...
Trigger. JavaScript Events              Designing and Building with Ajax   110
JavaScript                                                                 EventsTrigger. JavaScript Events• Ajax interact...
JavaScript                                                              EventsFirst, the EventsonAbort       onBluronChang...
JavaScript                                                                   EventsProblem in a Nutshell• Different event ...
Different Ways to Assign Events                                                                     JavaScript            ...
Confusing this Madness                                                                                 JavaScript         ...
Event Binding                                                                       JavaScript                            ...
Timing Issues                                                              JavaScript                                     ...
Memory Leaks                                                              JavaScript                                      ...
Yahoo! UI Event Manager                                                                                                   ...
Yahoo! UI Event Manager                                                                                                   ...
Update. The DOM          Designing and Building with Ajax   121
DHTML                                                                DOMUpdate. The DOM• Browsers represent the user inter...
DHTML                                                              DOMDOM Example• Represented as a tree of nodes         ...
DHTML                                                                  DOMUsing the DOM• JavaScript is the DOM manipulator...
DHTML                                                                  DOMFinding DOM Elements• document.getElementById• P...
DHTML                                                                DOMDOM Manipulation• Creating new interface elements•...
Example of DOM Manipulation (Hello World)                                                                          DHTML  ...
DHTML                                                               DOMKeeping it Clean• Separate presentation style from ...
Keeping it Clean: Rules to live by                                                                           DHTML        ...
Semantic Markup Example                                                                                                   ...
Keeping it clean: Example                                                                                                 ...
Keeping it clean: Example                                                                                                 ...
Advanced DOM Manipulation: Drag and Drop                                                                                  ...
Advanced DOM Manipulation: Animation                                                                                      ...
Trigger       Operation   UpdateLearning Ajax• Learning Ajax, means understanding• Triggers (event or timer)• Operations (...
Summary      Designing and Building with Ajax   136
Trigger       Operation   UpdateAjax Architecture• The Ajax DNA (events, data, presentation) is just a restatement of Mode...
Trigger       Operation   UpdatePulling It All Together• Two Projects that• Shows XHR in action• Explores XML vs JSON     ...
Ajax ToolkitsDesigning and Building Ajax Applications with Ajax Toolkits                                       Bill W. Sco...
What a Toolkit Provides                  Designing and Building with Ajax   140
Evaluating Toolkits• What language is it targeted for?• Are you looking for XHR abstraction or high level?• Will you use X...
Ajax Toolkits: Open Source JavaScript LibrariesPrototype           Inspired by Ruby, simplifies DOM manipulation, events, A...
Ajax Toolkit: Commercial JavaScript LibrariesTIBCO GI            Very extensive framework with full IDE. Dozens of widgets...
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Ap Ams Bill
Upcoming SlideShare
Loading in...5
×

Ap Ams Bill

1,545

Published on

Jesse James Garrett:

http://www.jjg.net/elements/

Bill Scott:
http://looksgoodworkswell.blogspot.com/

UX design and Ajax design patterns gurus JJ Garrett and Bill Scott (Copyrights from Garret/ Adaptive Path and Scott/ Yahoo, 2003) Courtesy of Garrett and Scott, 2005.

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,545
On Slideshare
0
From Embeds
0
Number of Embeds
26
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Ap Ams Bill"

  1. 1. DNA of Ajax ApplicationsDesigning and Building Ajax Applications with Patterns Bill W. Scott, Y! Ajax Evangelist b.scott@yahoo.com
  2. 2. Background• Games, research, science, military, biz• Apps, frameworks, widget sets• Developer, designer• Object-oriented background• Software architect, user experience manager• Yahoo! Ajax Evangelist, Yahoo! Patterns Curator• http://looksgoodworkswell.com Designing and Building with Ajax 2
  3. 3. Ajax at Yahoo!• Acquisition of Oddpost led to mission to evangelize Ajax goodness throughout Yahoo• Summer 2005 - Ajax Evangelism Team Founded• Doug Crockford - JSON, Y! DHMTL Architect• Iain Lamb - Founder of Oddpost/Y!Mail Beta• Me Designing and Building with Ajax 3
  4. 4. Yahoo! Pattern Library Release http://developer.yahoo.net/ypatterns/ Designing and Building with Ajax 4
  5. 5. yuiblog.comhttp://yuiblog.com Designing and Building with Ajax 5
  6. 6. Yahoo! Patterns Discussion Grouphttp://groups.yahoo.com/group/ydn-patterns/ Designing and Building with Ajax 6
  7. 7. Current Set of Patterns Breadcrumbs. Module Tabs. Navigation Tabs. Auto Complete. Pagination. Item Pagination. Search Pagination. Ratings and Reviews. Architecture of a Review. Rating an Object. Writing a Review. Drag and Drop. Drag and Drop Modules. Transition. Dim. Brighten. Cross Fade. Contract. Expand. Fade In. Fade Out. Move. Self-Healing. Slide. Highlight. Invitation. Cursor Invitation. Drop Invitation. Tool Tip Invitation. Hover Invitation. Designing and Building with Ajax 7
  8. 8. Rich Design Patterns Drag and Drop. Drag and Drop Modules. In Page Editing. In Page Custom Editing. Direct State Editing. Grid Cell Editing. Inline Custom Editing. Inline Tag Editing. Popup Custom Editing. Slide-out Custom Editing. Inline Text Editing. Persistent Portals. Inline Reordering. Indication. Busy Indication. Cursor Busy. In Context Busy. In Context Progress. Inline Status. Character Counter. Auto Complete. Balloon Error Tip. Deferred Content Loading. Dynamic Goal. Narrowing Choices. Refining Search. Live Search. Dynamic Filter. Invitation. Cursor Invitation. Drop Invitation. Tool Tip Invitation. Hover Invitation. Detail Zoom. Opacity Focus. Configurable Module - Faceplate. Configurable Module - Flip It. Configurable Module - Inline Configure. Configurable Module - Slide Out Drawer. Slide Out. Flip. Opacity Fade. Endless Scrolling. Expandable Paging Boundary. Fresh Content. Hover Detail. In Place Drill Down. Inline Assistant. Inline Validation. Validate Then Suggest. On Demand Refresh. Periodic Refresh. Resizable Modules. Scrolling Modules. Auto Save. In Context Tools. Remembered Collection. Remembered Preferences. Auto Form Fill. Rating an Object. Transition. Brighten Transition. Cross Fade Transition. Dim Transition. Expand Transition. Fade In Transition. Fade Out Transition. Flip Transition. Move Transition. Self-Healing Transition. Collapse Transition. Slide Transition. Rich Internet Object. Available. Selected. Identifiable Object. Designing and Building with Ajax 8
  9. 9. Y! Patterns as a Platform (Web 2.0) Yahoo! service responds with a JSON representation of a pattern. Allows anyone to mashup the patterns into a corporate pattern library Pattern Service Corporate Branded Pattern Site (mashup) Designing and Building with Ajax 9
  10. 10. Yahoo! UI Library Auto Complete Tree Slider Calendar Menu Windowing Animation Drag & Drop XHR Event DOM Designing and Building with Ajax 10
  11. 11. Richness Designing and Building with Ajax 11
  12. 12. Defining Richness: Web in 3D• Interaction Dimension Interaction event• Data Dimension Data Presentation response• Presentation Dimension Designing and Building with Ajax 12
  13. 13. Classic Web• Interaction page course-grained Interaction• Data Data loaded with the page or obtained via refresh Presentation• Presentation: refresh boundary page-based updates Data Designing and Building with Ajax 13
  14. 14. Classic Web Illustrated browser Http My Profile Response Photo Name Joe Smith Server Name Gender Male Gender Age 27 Age Submit Http Edit Request Interaction Data Presentation event response Designing and Building with Ajax 14
  15. 15. Ajax = Just-in-Time. Immediacy. Just-in-time dataJust-in-time presentation Just-in-time logic Designing and Building with Ajax 15
  16. 16. Ajax Model - New & Improved!• New! Deeper Interaction• Now with Just-in-Time Interaction Data & Just-in-Time Logic! Data★ XMLHttpRequest (XHR) is Presentation the secret sauce!• Now with Richer Interface!• All dimensions are closer Designing and Building with Ajax 16
  17. 17. Ajax Illustrated browser My Profile onreadystatechange Name Joe Smith Tim Jones Server Gender Male XHR Age 27 Save Object send() Interaction Data Presentation event response Designing and Building with Ajax 17
  18. 18. AJAX vs Ajax• AJAX = Asynchronous JavaScript and XML• Strict definition is using XMLHttpRequest (XHR) to retrieve XML within a web page• Ajax = The set of technologies that allow web applications to provide rich interaction, just-in-time information and dynamic interfaces without required page refresh• The Secret Sauce XHR• Ajax = XHR + DHTML (HTML, CSS, JavaScript) + Rich design Designing and Building with Ajax 18
  19. 19. Other Remote Scripting Techniques• Hidden IFrame• <img> src• <script> src hack• CSS href hack• JS to faceless Java applets• JS to faceless Flash• NO CONTENT Response• Cookies Designing and Building with Ajax 19
  20. 20. Patterns Designing and Building with Ajax 20
  21. 21. Rich Design Patterns Drag and Drop. Drag and Drop Modules. In Page Editing. In Page Custom Editing. Direct State Editing. Grid Cell Editing. Inline Custom Editing. Inline Tag Editing. Popup Custom Editing. Slide-out Custom Editing. Inline Text Editing. Persistent Portals. Inline Reordering. Indication. Busy Indication. Cursor Busy. In Context Busy. In Context Progress. Inline Status. Character Counter. Auto Complete. Balloon Error Tip. Deferred Content Loading. Dynamic Goal. Narrowing Choices. Refining Search. Live Search. Dynamic Filter. Invitation. Cursor Invitation. Drop Invitation. Tool Tip Invitation. Hover Invitation. Detail Zoom. Opacity Focus. Configurable Module - Faceplate. Configurable Module - Flip It. Configurable Module - Inline Configure. Configurable Module - Slide Out Drawer. Slide Out. Flip. Opacity Fade. Endless Scrolling. Expandable Paging Boundary. Fresh Content. Hover Detail. In Place Drill Down. Inline Assistant. Inline Validation. Validate Then Suggest. On Demand Refresh. Periodic Refresh. Resizable Modules. Scrolling Modules. Auto Save. In Context Tools. Remembered Collection. Remembered Preferences. Auto Form Fill. Rating an Object. Transition. Brighten Transition. Cross Fade Transition. Dim Transition. Expand Transition. Fade In Transition. Fade Out Transition. Flip Transition. Move Transition. Self-Healing Transition. Collapse Transition. Slide Transition. Rich Internet Object. Available. Selected. Identifiable Object. Designing and Building with Ajax 21
  22. 22. Principle. Immediacy. (Give Live Feedback)pattern. Live Suggest.pattern. Auto Complete. Designing and Building with Ajax 22
  23. 23. Keep the goal in mindDesign for immediacyIs it narrowing or is it distractingUse feedback to boost confidenceLet the user iterate where possible Just-in-time dataJust-in-time logic Designing and Building with Ajax 23
  24. 24. Keep the goal in mindDesign for immediacy Keep the user engagedIs it narrowing or is it distracting Time passes fasterUse feedback to boost confidence Look for engaging momentsLet the user iterate where possible Designing and Building with Ajax
  25. 25. Keep the goal in mindDesign for immediacy Keep the user engagedIs it narrowing or is it distracting Time passes fasterUse feedback to boost confidence Look for engaging momentsLet the user iterate where possibleUse live-previewsLook before you leap Designing and Building with Ajax 25
  26. 26. Keep the goal in mindDesign for immediacy Keep the user engagedIs it narrowing or is it distracting Time passes fasterUse feedback to boost confidence Look for engaging momentsLet the user iterate where possible Keep feedback focused Keep it in contextUse live-previews Updating too many areas at once will be confusingLook before you leap Show dynamically what is relevant Avoid creating feedback noise/jitter Designing and Building with Ajax 26
  27. 27. Principle. Directness. (Keep it Direct) pattern. Inline Editing.pattern. Drag and Drop. pattern. In Context Tools. Designing and Building with Ajax 27
  28. 28. Prefer interaction within the pageWhat about discoverability? Designing and Building with Ajax 28
  29. 29. Prefer interaction within the pageWhat about discoverability? Use direct editing on page content What about save/cancel? Avoid page jitter Reduce the feeling of modes Designing and Building with Ajax 29
  30. 30. Prefer interaction within the pageWhat about discoverability? Use direct editing on page content What about save/cancel? Avoid page jitter Reduce the feeling of modesProvide in-context toolsOnly good for single operationsCan actually slow you down Designing and Building with Ajax 30
  31. 31. 1Prefer interaction within the pageWhat about discoverability? Use direct editing on page content What about save/cancel? Avoid page jitter Reduce the feeling of modes Use drag and drop where appropriate Not for simply setting an attributeProvide in-context tools Good for layout changes or containmentOnly good for single operations Needs transitionsCan actually slow you down Designing and Building with Ajax 31
  32. 32. Principle. Invitational. (Offer an Invitation)pattern. Hover Invitation. pattern. Drop Invitation.pattern. Tooltip Invitation + Hover Invitation. Designing and Building with Ajax 32
  33. 33. Make it engagingUse lightweight events as a welcome matRediscover the hover Designing and Building with Ajax 33
  34. 34. 3 Offer an InvitationMake it engagingUse lightweight events as a welcome mat Keep actions out of itRediscover the hover Don’t make the user afraid to explore Don’t proselytize Designing and Building with Ajax 34
  35. 35. Make it engagingUse lightweight events as a welcome mat Keep actions out of itRediscover the hover Don’t make the user afraid to explore Don’t proselytizeGet the actors involvedHover InvitationCursor InvitationTooltip Invitation Designing and Building with Ajax
  36. 36. Make it engagingUse lightweight events as a welcome mat Keep actions out of itRediscover the hover Don’t make the user afraid to explore Don’t proselytize Use invitations to aid discoverability Two challenges: idiom & featureGet the actors involved Adding signposts, always-on clues doesn’t scaleHover Invitation Add tours, help pedals, tips, spotlightsCursor InvitationTooltip Invitation Designing and Building with Ajax 36
  37. 37. Principle. In Page Interaction. (Cross Borders Reluctantly)pattern. Endless Scrolling. pattern. In Context Expand. pattern. Inline Assistant.pattern. Hover Details. pattern. Lightweight Popup + Lightbox Designing and Building with Ajax 37
  38. 38. Rethink process flowsIts the user’s model, not the page modelEvery page jump is a mental speed bump Designing and Building with Ajax 38
  39. 39. Rethink process flowsIts the user’s model, not the page model Rethink pagingEvery page jump is a mental speed bump Its the user’s model, not the paging model Use scrolling for “owned” data Watch out for dual scroll bar issue Designing and Building with Ajax 39
  40. 40. Rethink process flowsIts the user’s model, not the page model Rethink pagingEvery page jump is a mental speed bump Its the user’s model, not the paging model Use scrolling for “owned” data Watch out for dual scroll bar issuePlan for linking, crawling and back buttonNot everything is a single page applicationWhat will the user think the back button does? Designing and Building with Ajax 40
  41. 41. Use overlaysFor momentary interruptionReplace page transitionWhen editing an individual, more complex itemBe symmetricalNot disturb the page Designing and Building with Ajax 41
  42. 42. Use overlaysFor momentary interruption Use in-context expandsReplace page transition For editing part of a collectionWhen editing an individual, more complex item Need to see surrounding contextBe symmetrical For managing content modulesNot disturb the page Designing and Building with Ajax 42
  43. 43. Principle. Light Footprint. (Keep a Light Footprint) pattern. Rating an Object.pattern. Remembered Collection. pattern. In Page Action. Designing and Building with Ajax 43
  44. 44. Watch your click weightKeep actions immediate and lightCount “clicks” Designing and Building with Ajax 44
  45. 45. Watch your click weightKeep actions immediate and lightCount “clicks” Design for engaging moments Use invitations Keep it fun, exciting and light Treat it like an impulse aisle Designing and Building with Ajax 45
  46. 46. Watch your click weightKeep actions immediate and lightCount “clicks” Design for engaging moments Use invitations Keep it fun, exciting and light Treat it like an impulse aisleUse lightweight eventsHoverBlur, focusClick. Avoid double-click Designing and Building with Ajax 46
  47. 47. Principle. Cinematic Effects. (Use Transitions)pattern. Fade Transition + Self-Healing Transition.pattern. Slide + Animate. pattern. Spotlight. Designing and Building with Ajax 47
  48. 48. Speak to the BRAINUnderstanding attention processingSending the wrong message Designing and Building with Ajax 48
  49. 49. Speak to the BRAINUnderstanding attention processing What you can communicateSending the wrong message Speed up time Slow down time Show state change Show relationships between objects Designing and Building with Ajax 49
  50. 50. Speak to the BRAINUnderstanding attention processing What you can communicateSending the wrong message Speed up time Slow down time Show state change Show relationships between objects Keep it sane “Cut in half” rule of thumb Use a “contrast knob” approach Don’t overuse Designing and Building with Ajax 50
  51. 51. Simple observations• The more rapid the change the more important the event.• Rapid movement is seen as more important than rapid color change.• Movement toward the user is seen as more important than movement away from the user.• Very slow change can be processed without disrupting the users attention.• Animation can be used to communicate where an object was and now is Designing and Building with Ajax 51
  52. 52. Principle. Rich Objects. (Think in Objects)pattern. Shareable Object. Designing and Building with Ajax 52
  53. 53. 7 Think in ObjectsRethinking the modelWhat is the user’s mental model?How to distinguish from content? Designing for Ajax 53
  54. 54. 7 Think in ObjectsRethinking the modelWhat is the user’s mental model? The power of sharingHow to distinguish from content? Bloggable, shareable, findable How to dial-in community Collections Designing for Ajax 54
  55. 55. 7 Think in ObjectsRethinking the modelWhat is the user’s mental model? The power of sharingHow to distinguish from content? Bloggable, shareable, findable How to dial-in community CollectionsWeb 2.0 as a platformRich objects fit the SOA modelCreates a good separation of concernsMashups Designing for Ajax 55
  56. 56. So What Can XHR Do?• Make a request• Return a response• And do it asynchronously response XHR Object request Designing and Building with Ajax 56
  57. 57. Ajax Pattern DNA• Every Ajax design pattern consists of a• Trigger (event or timer)• Operation (ajax)• Update (dom) Trigger Operation Update Designing and Building with Ajax 57
  58. 58. Trigger• Every pattern of interaction starts with• a user event• a timer event mouseout hover keypress keydown mousedowndrop filter choices mouseup drag click mousedown select focus blur resize move timeout Trigger Designing and Building with Ajax 58
  59. 59. OperationFive basic operations define what you can do• Lookup I can get information when I need it• Persist I can save in real-time• Validate I can prevent errors early• Invoke I can make things happen now• Message I can communicate instantly Operation Designing and Building with Ajax 59
  60. 60. Operation. LookupI can get information when I need it Auto Complete. Deferred Content Loading. Dynamic Goal. Narrowing Choices. Refining Search. Live Search. Dynamic Filter. Detail Zoom. Endless Scrolling. Expandable Paging Boundary. Fresh Content. Hover Detail. In Place Drill Down. On Demand Refresh. Periodic Refresh. Resizable Modules. Scrolling Modules. Auto Form Fill. Trigger Lookup Operation Update Designing and Building with Ajax 60
  61. 61. Lookup live search Keystroke Lookup Dropdown lookup results Updated Designing and Building with Ajax 61
  62. 62. Lookup endless scrolling Rico LiveGrid Yahoo! Mail Beta (Oddpost) Scroll Grid Event Lookup Cells lookup results Updated Designing and Building with Ajax 62
  63. 63. Operation. PersistI can save in real-time Drag and Drop Modules. In Page Editing. In Page Custom Editing. Direct State Editing. Grid Cell Editing. Inline Custom Editing. Inline Tag Editing. Popup Custom Editing. Slide-out Custom Editing. Inline Text Editing. Inline Reordering. Auto Save. Remembered Collection. Remembered Preferences. Rating an Object. Trigger Persist Update persist status optional Designing and Building with Ajax 63
  64. 64. Persist inline edit Save New Button Persist Text persist status Updated Designing and Building with Ajax 64
  65. 65. Persist persistent portals Drop Drop Module Persist Accepted persist status Designing and Building with Ajax 65
  66. 66. Operation. ValidateI can prevent errors early per field validate keystroke validate inline form validate invalid but suggest Trigger Validate Update validate status Designing and Building with Ajax 66
  67. 67. Operation. InvokeI can make things happen now fire and forget lightweight action Trigger Invoke Update invoke status Designing and Building with Ajax 67
  68. 68. Operation. MessageI can communicate instantly two-way chat real-time auction collaborative white board Message Event Message Trigger Sent message out Check Message Message Update Trigger Received poll message in Designing and Building with Ajax 68
  69. 69. Update • User interface changes to reflect what is happening slideout slideover dropdown popup balloonbusyicon mousecursor fade dim brighten selfhealing additems finishedindicator remove show hide resize Update Designing and Building with Ajax 69
  70. 70. Five Operations Define Ajax• Lookup. I can get information when I need it• Persist. I can save in real-time• Validate. I can prevent errors early• Invoke. I can make things happen now• Message. I can communicate instantly Designing and Building with Ajax 70
  71. 71. Steps to Understanding Ajax• Use the patterns• Understand XHR - operations• Understand event management - triggers• Know the tricks of the DOM - update• Understand the issues that surround Ajax• We will discuss these issues this afternoon Designing and Building with Ajax 71
  72. 72. Pattern-O-Matic Drag & Lightweight Onscroll Select Hover Content Search Drop UI Design Persist Keypress Trigger Drop Blur Filters Event Module + Operation Lookup Persist + Grid Cell Popup Reflects Module Update Results Down Update Updates Shows OK Status Updates Refined = Persistent Refining Endless Hover Inline Auto Ajax Pattern Design Complete Scrolling Search Portals Detail Edit Pattern Complete Pattern Detail Drag and Drop Modules. In Page Editing. In Page Custom Editing.Auto Complete.Editing. Grid Cell Editing. Inline Custom Editing. Direct State Deferred Content Loading. Dynamic Goal. Narrowing Choices. Tag Editing. Popup Custom Editing. Slide-out CustomZoom. Inline Refining Search. Live Search. Dynamic Filter. Detail Editing. Inline Text Editing. Inline Reordering. Auto Save.Endless Scrolling. Expandable Paging Boundary. Fresh Content. Hover Detail. In Place Drill Down. On DemandPreferences. Rating an Remembered Collection. Remembered Refresh. Periodic Refresh. Object. Resizable Modules. Scrolling Modules. Auto Form Fill. Designing and Building with Ajax 72
  73. 73. Ajax 101A Look Under the Hood Bill W. Scott, Y! Ajax Evangelist b.scott@yahoo.com
  74. 74. Operation. Using XHR Designing and Building with Ajax 74
  75. 75. Ajax XHROperation. Using XHR• The five operations are not built into XHR• The simple send/response mechanism can be used to implement lookup, persist, validate, invoke and message• To create these operations, one must understand how to use XHR• A simple HelloWorld example will illustrate using XHR Designing and Building with Ajax 75
  76. 76. Ajax XHRSimple Ajax ‘Hello World’ <?xml version="1.0" ?> request <root> XHR This data was brought Object to you by Ajax! data </root> /response.xml response <h2>Ajax Hello World</h2> <p>Clicking the link below will use XHR to fetch the data and then show the result in the box below.</p> <span class="ajaxlink" onclick="makeRequest(test.xml)"> Make an ajax request for data </span> <div id="helloArea"></div> /index.html• Clicking the link makes an XHR request• Response is inserted into the area outlined in blue Designing and Building with Ajax 76
  77. 77. Ajax XHRAjax How To1. Create a request object2. Write a callback3. Make the request4. Parse the response Designing and Building with Ajax 77
  78. 78. 1. Create a Request Object 1. Createvar xhr = null;if (window.XMLHttpRequest) { browser is mozilla or safari or opera then create a XMLHttpRequest(); xhr = newnew XMLHttpRequest xhr.overrideMimeType(‘text/xml’);otherwise it is IE then} else if (window.ActiveXObject) { create a ActiveXObject(“Microsoft.XMLHTTP”); xhr = newnew ActiveXObjectotherwise} else { error - browser does not support XMLHttpRequest alert(“Perhaps your browser doesn’t support Ajax.”);}• IE5, 5.5, 6 implements XHR as an ActiveX object (Msxm12.XMLHTTP/Microsoft.XMLHTTP)• Mozilla 1.0+, Safari 1.2+, Opera 8+, IE7 provide XMLHttpRequest object natively• All XHR objects have same methods & properties Designing and Building with Ajax 78
  79. 79. Ajax XHRXHR MethodsMethod Descriptionopen(“method”, “url”, [, asynchFlag [, Sets up the request object for sending a“username” [, “password”]]]) requestsend(content) Sends the request to the server. Can be null.abort() Stops the request.getAllResponseHeaders() Returns all response headers for the HTTP request as key/value pairs.getReponseHeader(“header”) Returns the string value of the specified header.setRequestHeader(“header”, “value”) Sets the specified header to the supplied value. Source: Foundations of Ajax - APress Designing and Building with Ajax 79
  80. 80. Ajax XHRXHR PropertiesProperty Descriptiononreadystatechange The event handler that fires at every state change.readystate The state of the request: 0=uninitialized, 1=loading, 2=loaded, 3=interactive, 4=completeresponseText The response from the server as a text stringresponseXML The response from the server as an XML documentstatus The HTTP status code from the server for the request object: 200: Ok; 201: Created; 400: bad request, 403: Forbidden; 500: internal sever errorstatusText The text version of the HTTP status code Designing and Building with Ajax 80
  81. 81. 2. Write a Callback Ajax XHRfunction handleAjaxResponse handleAjaxResponse()begin{ do something with // we will handle the ajax responsereturned from XHR data that is here...end}• JavaScript callback function is invoked when the readystate changes on the XHR object Designing and Building with Ajax 81
  82. 82. 3. Make the Request Ajax XHRset onreadystatechange tohandleAjaxResponse;- handleAjaxResponsexhr.onreadystatechange = callback functionopen a request ‘response.xml’,xhr.open(‘GET’,on the xhr objecttrue);send the request through the xhr objectxhr.send(null);• The JavaScript function handleAjaxResponse will be invoked when the readystate property changes on the XHR object server must be accessible via relative url X• Same site rule response• ‘GET’ or ‘POST’ XHR Object √ request• Asynchronous flag X Designing and Building with Ajax 82
  83. 83. 3. Make the Request - Choosing Between GET and POST Ajax XHR• Use GET for • For retrieve • REST services • When passing parameters • Idempotent URLs • Small amount of data• Use POST for • Modification • Large amounts of data passed to server • Non-idempotent URLs Designing and Building with Ajax 83
  84. 84. 3. Make the Request: Handling the Request on the Server Side• Its just a normal HTTPRequest • Normal mechanism for getting request parameters• Raw POST (xhr.send(someData)) • Java/JSP: request.getInputStream() - read as raw post • Rails: @request.raw_post • PHP: $data = file_get_contents(php://input) Designing and Building with Ajax 84
  85. 85. 4. Parse the Response Ajax XHRfunction handleAjaxResponse() handleAjaxResponse{begin if ((xhr.readystate == 4) && (xhr.status == 200)) { response is valid then var doc = xhr.responseXML; get responseXML var rootNode = doc.getElementsByTagName(root).item(0); get var helloArea = document.getElementById("helloArea"); get on the page helloArea.innerHTML=rootNode.firstChild.data; stuff the rootNode value into the helloArea DIV }endif}end• readystate values 0 – Uninitialized 1 – Loading 2 – Loaded 3 – Interactive 4 – Completed Designing and Building with Ajax 85
  86. 86. 4. Parse the Response: Formatting an XML Response on the Server Ajax XHR• XML version must be first line <?xml version="1.0" encoding="ISO-8859-1"?>• Set up response header’s Content-type “Content-Type”, “text/xml”• Use well-formed XML Designing and Building with Ajax 86
  87. 87. 4. Parse the Response: Handling an XML Response on the Client Ajax XHR• Use XHR property responseXML to get the response as an XML DOM (XmlDocument)• Use standard JavaScript DOM methods • Mozilla, Safari, Opera & IE support a common set of methods and properties • Watch out for IE only stuff (e.g., children property) • Watch out for whitespace issues• Other options • Use XML library for JS (e.g., XML for <script>) Designing and Building with Ajax 87
  88. 88. 4. Parse the Response: Xml Document API Ajax XHR Property/Method DescriptiondocumentElement Returns the root element of the documentfirstChild Is the first element within another element (the first child of the current node)lastChild Is the last element within another element (the last child of the current node)nextSibling Is the next element in the same nested level as the current onepreviousSibling Is the previous element in the same nested level as the current onenodeValue The value of a document elementgetElementsByTagName Used to place all elements into an object ???????? Designing and Building with Ajax 88
  89. 89. 4. Parse the Response: A little more parsing.<?xml version="1.0" ?><root> <contents> This data was brought to you by Ajax! </contents> <style> height:40px;width:250px;margin-top:20px;padding:20px;border:8px solid red; </style></root>function alertContents() { if (xhr.readyState == 4) { if (xhr.status == 200) { var response = xhr.responseXML.documentElement; var content = response.getElementsByTagName(contents)[0].firstChild.data; var style = response.getElementsByTagName(style)[0].firstChild.data; var helloArea = document.getElementById("helloArea"); helloArea.innerHTML=content; helloArea.style.cssText=style; } else { alert(There was a problem with the request.); } }} Designing and Building with Ajax 89
  90. 90. Handling the Response Ajax XHR• Two types: text, xml• Many formats text xml data data response html html XHR Object request JS JS json Designing and Building with Ajax 90
  91. 91. Handling the Response: Server-Side-GUI Method Ajax XHR• JavaScript generated on server-side• JavaScript is eval’ed on client side to generate GUI• Dangerous! text xml data data response html html XHR Object interface request JS JS code json Designing and Building with Ajax 91
  92. 92. Handling the Response: Direct-HTML Method Ajax XHR• HTML generated on server side• Stuffed into innerHTML of DOM element text xml data data response html html innerHTML XHR Object request JS JS json Designing and Building with Ajax 92
  93. 93. Handling the Response: View-From-Model Method Ajax XHR• Model data generated on server side• w3c DOM elements created from model data• Substitute model data into HTML strings and insert via innerHTML text xml data data model response html html XHR Object request JS JS json Designing and Building with Ajax 93
  94. 94. Ajax XHRJSON• JavaScript supports several string based notations• Allows the basic types to be represented as string literals• Strings are easy to pass over the wire• JSON (JavaScript Object Notation - json.org) Designing and Building with Ajax 94
  95. 95. JSON Response: Object Literal Ajax XHR {"name": "Jack B. Nimble", "at large": true, "grade": "A", "level": 3} name Jack B. Nimble at large true grade A level 3 Designing and Building with Ajax 95
  96. 96. JSON Response: Array Literal Ajax XHR ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] array of 7 named days [ [0, -1, 0], [1, 0, 0], [0, 0, 1] ] 3x3 array Designing and Building with Ajax 96
  97. 97. JSON Response: JSON is JavaScript Ajax XHR• JSONs simple values are the same as used in JavaScript• No restructuring is requested: JSONs structures are JavaScript!• JSONs object is the JavaScript object• JSONs array is the JavaScript array• Parsing is simple, native Designing and Building with Ajax 97
  98. 98. JSON Response: Parsing JSON Ajax XHR• Obtain responseText• Parse the responseText responseData = eval(( + responseText + )); OR responseData = JSON.parse(responseText); Designing and Building with Ajax 98
  99. 99. JSON Response: Y! JSON API Ajax XHR• http://api.search.yahoo.com/WebSearchService/V1/webSearch? appid=YahooDemo&query=finances&start=1&results=1&output=json { "ResultSet": { "totalResultsAvailable":"69200000", "totalResultsReturned":"1", "firstResultPosition":"1", "Result": { "Title":"Yahoo! Finance", "Summary":"manage the market and your money with Yahoo! Finance. Includes stock market quotes, business news, mutual funds, online bill pay, banking tools, loans, insurance, retirement planning, and tax tips and advice.", "Url":"http://finance.yahoo.com/", "ClickUrl":"http://finance.yahoo.com/", "ModificationDate":"1137225600", "MimeType":"text/html" } } } Designing and Building with Ajax 99
  100. 100. Building an Ajax Weather Widget Using an XML Service Server XHR Designing and Building with Ajax
  101. 101. REST Service - weather.com weather.com exposes its weather service via an URL that includes a partner key and license key http://xoap.weather.com/weather/local/95132? cc=*&link=xoap&prod=xoap&par=PARTNER_KEY&key=LICENSE_KEY Server XHR Designing and Building with Ajax 101
  102. 102. XML Response from weather.com <?xml version="1.0" encoding="ISO <cc> -8859-1"?> <lsup>1/21/06 7:53 PM PST</lsup> <weather ver="2.0"> <obst>San Jose, CA</obst> <head> <tmp>49</tmp> <locale>en_US</locale> <flik>46</flik> <form>MEDIUM</form> <t>Mostly Cloudy</t> <ut>F</ut> <icon>27</icon> <ud>mi</ud> <bar> <us>mph</us> <r>30.27</r> weather.com responds <up>in</up> <d>rising</d> with an XML response that <ur>in</ur> </bar> </head> <wind> describes the weather’s <loc id="95132"> <s>7</s> current conditions <dnam>San Jose, CA (95132)</ <gust>N/A</gust> dnam> <d>350</d> <tm>8:37 PM</tm> <t>N</t> <lat>37.4</lat> </wind> <lon>-121.86</lon> <hmid>80</hmid> <sunr>7:18 AM</sunr> <vis>10.0</vis> <suns>5:20 PM</suns> <uv> <zone>-8</zone> <i>0</i> </loc> <t>Low</t> </uv> <dewp>43</dewp> <moon>Server <icon>21</icon> <t>Waning Gibbous</t> </moon> </cc> </weather> Designing and Building with Ajax 102
  103. 103. Rico/Prototype Response<?xml version="1.0" encoding="ISO-8859-1"?><ajax-response> <response type="element" id="ccInfo"> <div class="weatherTitle">San Jose, CA (95132)</div> <div> <span><image id="ccImg" src="/images/weather/27.png"></image></span> <span class="weatherTemp">49°F</span> My server code translates </div> <div class="weatherDescr">Mostly Cloudy</div> the weather.com XML into a <div> Rico/Prototype ajax-response. <table cellspacing="0" cellpadding="0" border="0"> Notice the response is an HTML <tr class="weatherDetail"> <td class="weatherDetailTitle">Humidity:</td> code snippet. The response is of <td>80%</td></tr> type element, and mapped to <tr class="weatherDetail"> <td class="weatherDetailTitle">Barometer:</td> id=”ccInfo” <td>30.27&quot;</td></tr> <tr class="weatherDetail"> <td class="weatherDetailTitle">Wind:</td> <td>From N at 7 mph</td></tr> <tr class="weatherDetail"> <td class="weatherDetailTitle"></td> <td>gusting to N/A mph</td></tr> <tr class="weatherDetail"> <td class="weatherDetailTitle">Dewpoint:</td> <td>43°F</td></tr> <tr class="weatherDetail"> Server <td class="weatherDetailTitle">Heat Index:</td> XHR <td>46°F</td></tr> </table> </div> </response></ajax-response> Designing and Building with Ajax 103
  104. 104. Simple DIV Structure Defines the Accordion<div id="weather"> <div id="current"> <div id="currentHeader" class="accordionTabTitleBar"> Current Conditions </div> <div class="weatherTabContentBox"> <div class="weatherPanel" id="ccInfo"> </div> </div> </div> <div id="moon"> <div id="moonHeader" class="accordionTabTitleBar"> Moon </div> <div class="weatherTabContentBox"> <div class="weatherPanel" id="moonInfo"> </div> </div> </div> <div id="sun"> <div id="sunHeader" class="accordionTabTitleBar"> <script> Sunlight Summary onloads.push( accord ); </div> function accord() { <div class="weatherTabContentBox"> new Rico.Accordion( weather, <div class="weatherPanel" id="sunInfo"> {panelHeight:220, expandedBg:#39497b} ); </div> } </div> </script> </div></div> Designing and Building with Ajax 104
  105. 105. The Ajax Code function registerAjaxStuff() { ajaxEngine.registerRequest( getWeatherInfo, ajax_weather_info ); ajaxEngine.registerAjaxElement( ccInfo ); ajaxEngine.registerAjaxElement( moonInfo ); ajaxEngine.registerAjaxElement( sunInfo ); ajaxEngine.registerAjaxElement( sponsoredLinks ); $(zip).onkeydown = handleEnterKey.bindAsEventListener($(zip)); } function getWeatherInfo() { $(checkanother).style.visibility=visible; new Rico.Effect.Position( $(zipinput), 200, null, 100, 10); new Rico.Effect.FadeTo( frontdoor, 0, 100, 10, {complete:function() {$(frontdoor).style.display = none;}} ); ajaxEngine.sendRequest( getWeatherInfo, "zip=" + $(zip).value); } function resetWeather() { $(zipinput).style.left = 12px; $(checkanother).style.visibility=hidden; $(frontdoor).style.display = $(zip).focus(); new Rico.Effect.FadeTo( frontdoor, .99999, 100, 10, {complete:emptyContents}); } Designing and Building with Ajax 105
  106. 106. JSON Trip Finder Server XHR Designing and Building with Ajax 106
  107. 107. REST Service Request - Yahoo! Trip Planner - JSON Yahoo! Trip Planner exposes its service via an URL that requires a free partner key. Notice output=json. http://api.travel.yahoo.com/TripService/V1/tripSearch? appid=PARTNER_KEY&query=alaska&output=json Server XHR Designing and Building with Ajax 107
  108. 108. JSON Response {"ResultSet":{"firstResultPosition": 1,"totalResultsAvailable":"16","totalResultsReturned": 10,"Result":[ {"id":"351102","YahooID":"jk_95661","Title":"Cruise to Alaska from Vancouver","Summary":"Things to do: Whistler Blackcomb - Hiking,... Hotel: Hyatt Regency Vancouver, Howard Jho...","Destinations":"Vancouver, Anchorage, Juneau, North Vancouver, Ketchikan, Y! service responds with a JSON Se...","CreateDate":"1130437928","Duration":"16","Image": {"Url":"http://us.i1.yimg.com/us.yimg.com/i/travel/tg/ lp/cd/ text string, valid JavaScript 100x100_cde24409e413d4d6da27953f6ab0bbde.jpg","Height":"100",is object notation. This passed directly back as "Width":"66"},"Geocode":{"Latitude":"49.284801","Longitude":" -123.120499","precision":"not available"},"Url":"http:// the XHR result travel.yahoo.com/trip/?pid=351102&action=view"}, {"id":"400333","YahooID":"brdway_grl","Title":"Alaska","Summa ry":"Things to do: Mooses Tooth Pub and Pizzer... Restaurant: Orso, Simons & Seaforts Salo...","Destinations":"Anchorage","CreateDate":"1134676973" ,"Duration":"10","Image":{"Url":"http://us.i1.yimg.com/ us.yimg.com/i/travel/tg/poi/ca/ Server 100x100_ca605c44b47e20a731d3093b94afa37e.jpg","Height":"75"," Width":"100"},"Geocode":{"Latitude":"61.190361","Longitude":" -149.868484","precision":"not available"},"Url":"http://XHR travel.yahoo.com/trip/?pid=400333&action=view"}, ... ]}} Designing and Building with Ajax 108 89
  109. 109. The Ajax/JSON Code<script>function showResponse() { if (xhr.readyState == 4) { if (xhr.status == 200) { var jsontext = xhr.responseText; var helloArea = document.getElementById("helloArea"); var theTrip = eval( ( + jsontext + ) ); var tripPlanHTML = ""; for(var i=0; i<theTrip.ResultSet.totalResultsReturned; i++) { var result = theTrip.ResultSet.Result[i]; tripPlanHTML = tripPlanHTML + <div style="padding:4px;border:1px solid gray;width:+result.Image.Width+;"><imgsrc="+result.Image.Url+" width="+result.Image.Width+"height="+result.Image.Height+"></img></div>+<div ><a href="+result.Url+"><span style="font-weight:bold;font-size:18px;">+result.Title+</span></a></div><div>+result.Summary+</div><br/>; } helloArea.innerHTML=tripPlanHTML; } else { alert(There was a problem with the request.); } }}</script><h2>Find Trip Plans (using Ajax &amp; JSON)</h2><p>Search for Trip Plans</p><input id="searchCriteria" type="text"> <input value="Search" type="button"onclick="makeRequest(response_trip_planner_mult_json.jsp, document.getElementById(searchCriteria).value)"><div style="height:300px;width:420px;margin-top:8px;padding:8px;"id="helloArea"></div> Designing and Building with Ajax 109
  110. 110. Trigger. JavaScript Events Designing and Building with Ajax 110
  111. 111. JavaScript EventsTrigger. JavaScript Events• Ajax interactions are kicked off by event & timer triggers• There are issues with event management within the browsers• You do need to understand these implications to write good Ajax applications Designing and Building with Ajax 111
  112. 112. JavaScript EventsFirst, the EventsonAbort onBluronChange onClickonDblClick onDragDroponError onFocusonKeyDown onKeyPressonKeyUp onLoadonMouseDown onMouseMoveonMouseOut onMouseOveronMouseUp onMoveonReset onResizeonSelect onSubmitonUnload Designing and Building with Ajax 112
  113. 113. JavaScript EventsProblem in a Nutshell• Different event models• Timing Issues• Confusing madness around the this pointer• Browser incompatibilities• Memory leak issues Designing and Building with Ajax 113
  114. 114. Different Ways to Assign Events JavaScript Events• Element Attributes • <element onclick=”func()” >• Element Properties (function reference) • element.onclick=func;• Event Binding • w3c: addEventListener, removeEventListener • IE: attachEvent, detachEvent Designing and Building with Ajax 114
  115. 115. Confusing this Madness JavaScript Events• Element Attributes <a href=”#” onclick=”clickHandler(this)”> function clickHandler(anchorDOMElem) { // this == window --> window owns the function // anchorDOMElem was set to anchor DOM element this = anchorDOMElem; // fix this pointer }• Element Properties myAnchor.onclick=clickHandler; function clickHandler() { //this == anchorDOMElem --> anchorDOMElem owns the function }• Event Binding function AnchorLink(anchorDOMElem) { this.anchorDOMElem = anchorDOMElem; this.anchorDOMElem.onclick = this.clickHandler; this.anchorDOMElem.anchorLinkObj = this; } AnchorLink.prototype.clickHandler = function() { // this == anchorDOMElem, not AnchorLink object // confusing since this normally refers to AnchorLink // grab our normal this anchorLinkObj = this.anchorLinkObj; } Designing and Building with Ajax 115
  116. 116. Event Binding JavaScript Events• Supports arbitrary number of event handlers• Provides a way to remove events• The model defines capture & bubble flow• But, no way to get list of handlers• And remember the browsers play differently: Internet Explorer Mozilla (FF), Safari, Opera [W3C] attachEvent() addEventListener() detachEvent() removeEventListener() this == window object this == DOM event object Designing and Building with Ajax 116
  117. 117. Timing Issues JavaScript Events• Attempting to attach events before the page is loaded will cause problems• Do it on the onload Designing and Building with Ajax 117
  118. 118. Memory Leaks JavaScript Events• IE’s garbage collection does simple reference counting• Attaching events and not removing them when finished will cause memory leaks• Can use an Observer style pattern to cache event handlers and at the end clean them up Designing and Building with Ajax 118
  119. 119. Yahoo! UI Event Manager JavaScript Events• Standardizes event binding • Attach an event var oElement = document.getElementById("elementid"); function fnCallback(e) { alert("click"); } YAHOO.util.Event.addListener(oElement, "click", fnCallback); • Attach multiple events var ids = ["el1", "el2", "el3"]; // array can contain object references, element ids, or both function fnCallback(e) { alert(this.id); } YAHOO.util.Event.addListener(ids, "click", fnCallback);• Handles automatic scope correction • By default “this” refers to the DOM element that the event was attached to • Can be overridden• First parameter is the event object• Pass arbitrary objects to event handler Designing and Building with Ajax 119
  120. 120. Yahoo! UI Event Manager JavaScript Events• Automatic Listener Cleanup• Custom Events • For custom objects or overriding events on widgets• onAvailable event • Define a function that will execute as soon as an element is detected in the DOM (during load) <script type="text/javascript"> function TestObj(id) { YAHOO.util.Event.onAvailable(id, this.handleOnAvailable, this); } TestObj.prototype.handleOnAvailable = function(me) { alert(this.id + " is available"); } var obj = new TestObj("myelementid"); </script> <div id="myelementid">my element</div> Designing and Building with Ajax 120
  121. 121. Update. The DOM Designing and Building with Ajax 121
  122. 122. DHTML DOMUpdate. The DOM• Browsers represent the user interface as a set of objects (or elements)• Since a page has a hierarchy of containment, each of these elements are related as parent-child or siblings• This takes the shape of a tree• The tree of elements is called the document object model or DOM. Specifically the Browser DOM.• Any change to the DOM structure or a DOM element is reflected immediately on the web page Designing and Building with Ajax 122
  123. 123. DHTML DOMDOM Example• Represented as a tree of nodes Designing and Building with Ajax 123
  124. 124. DHTML DOMUsing the DOM• JavaScript is the DOM manipulator• Use it to• Find DOM elements• Add new elements• Remove elements• Modify element attributes • Position elements • Style elements Designing and Building with Ajax 124
  125. 125. DHTML DOMFinding DOM Elements• document.getElementById• Prototype library shortcut: $(“idName”) or $(id)• Yahoo! library shortcuts: • YAHOO.util.Dom.get(“idName”) • getElementByClassName• parentNode• childNodes• Yahoo! library has ways to find ancestors Designing and Building with Ajax 125
  126. 126. DHTML DOMDOM Manipulation• Creating new interface elements• innerHTML, createElement(), createTextNode(), appendChild()• Changing element styles• Visual attributes• Geometry• Y!UI positioning, region detection• Y!UI classname & style normalization Designing and Building with Ajax 126
  127. 127. Example of DOM Manipulation (Hello World) DHTML DOM<h2>Ajax Hello World</h2><p>Clicking the link below will use XHR to fetch the data andthen show the result in the box below.</p><span class="ajaxlink" onclick="makeRequest(response.jsp)">Make an ajax request for data</span><div id="helloArea"></div>var helloArea = document.getElementById("helloArea");helloArea.innerHTML=rootNode.firstChild.data; 127 Designing and Building with Ajax
  128. 128. DHTML DOMKeeping it Clean• Separate presentation style from content with CSS• Supports degradability• Supports accessibility• Simplifies maintenance• http://www.mezzoblue.com/css/cribsheet/• Designing and Building with Ajax 128
  129. 129. Keeping it Clean: Rules to live by DHTML DOM• Avoid these elements: • b, big, hr, i, small, sub, sup, tt • basefont, center, dir, font, isindex, menu, s, strike, u, tfoot • br is ok for content breaks; not layout• Make your HTML meaningful • List structures as ul, li • Tree structures as nested ul, li • Containers as div• Use css selectors (contextual) • Reduces the number of classes • Avoid inline styles • Designing and Building with Ajax 129
  130. 130. Semantic Markup Example DHTML<div id="weather"> DOM <div id="current"> <div id="currentHeader" class="accordionTabTitleBar"> Current Conditions </div> <div class="weatherTabContentBox"> <div class="weatherPanel" id="ccInfo"> </div> </div> </div> <div id="moon"> <div id="moonHeader" class="accordionTabTitleBar"> Moon </div> <div class="weatherTabContentBox"> <div class="weatherPanel" id="moonInfo"> </div> </div> </div> <div id="sun"> <div id="sunHeader" class="accordionTabTitleBar"> Sunlight Summary </div> <div class="weatherTabContentBox"> <div class="weatherPanel" id="sunInfo"> </div> </div> </div></div> new Rico.Accordion( weather, {panelHeight:220, expandedBg:#39497b} Designing and Building with Ajax 130
  131. 131. Keeping it clean: Example DHTML<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> DOM<html><head><title>Make this page more semantic</title></head><body><div class="page-title">Make this page more semantic</div><div><div class="module-title">Module Title</div><span class="time"><i>12:40pm Wed Mar 29</span></i><div class="para">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismodtincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci </div></div><p><div><i>ìWeb users ultimately want to get at data quickly and easily. They dont care as much aboutattractive sites and pretty design.î</i></div> says <b>Tim Berners Lee</b>, inventor of the World Wide Web,although Im sure many visual designers would beg to differ. <u>"The web isnt print!"</u> - Chanel.</p><table> <tr> <td class="heading">column 1</td> <td class="heading">column 2</td> <td class="heading">column 3</td> </tr> <td class="data">data cell 1</td> <td class="data">data cell 2</td> <td class="data">data cell 3</td> </tr></table></body></html> Designing and Building with Ajax 131
  132. 132. Keeping it clean: Example DHTML<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> DOM<html><head><title>Make this page more semantic</title></head><body><h1>Make this page more semantic</h1><h2>Module Title</h2><em class="time" title="time stamp">12:40pm Wed Mar 29</em><blockquote>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinciduntut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci </blockquote><blockquote cite="Tim Berners Lee"><p>'Web users ultimately want to get at data quickly and easily. They dont care as much about attractivesites and pretty design.'</p></blockquote> says <cite>Tim Berners Lee</cite>, inventor of the World WideWeb, although Im sure many visual designers would beg to differ. <q>The web isnt print!</q> -<cite>Chanel</cite>.<table summary="this months numbers"> <caption>Q1 Financials</caption> <thead> <tr> <th scope="col">column 1</th> <th scope="col">column 2</th> <th scope="col">column 3</th> </tr> </thead> <tbody> <td class="data">data cell 1</td> <td class="data">data cell 2</td> <td class="data">data cell 3</td> </tr> </tbody></table></body></html> Designing and Building with Ajax 132
  133. 133. Advanced DOM Manipulation: Drag and Drop DHTML DOM ... <script type="text/javascript"> YAHOO.example.DDApp = function() { var dd; return { init: function() { var dd = new YAHOO.util.DD("dragDiv"); } } } (); YAHOO.util.Event.addListener(window, "load", YAHOO.example.DDApp.init); </script> <style type="text/css"> #dragDiv { background:url(images/macosxlogo.gif) 0 0 no-repeat; height:100px; width:70px; } </style> </head> <body> <h2>Drag and Drop</h2> <p>The Mac logo is draggable</p> <div id="dragDiv"></div> </body> ... Designing and Building with Ajax 133
  134. 134. Advanced DOM Manipulation: Animation DHTML<html> DOM<head><style>#anim { background:#ccc;width:10px;height:20px;font-size:10%;}</style><script type="text/javascript">YAHOO.namespace(example.anim);YAHOO.example.anim.init = function() { var myAnim = new YAHOO.util.Anim(anim, { width: {to: 200}, height: {to: 150}, fontSize: {from: 20, to: 120, unit: %}, opacity: {from: 0.25, to: 1.0 }}, 1, YAHOO.util.Easing.easeOut); var animate = function(e) { myAnim.animate(); return false; } YAHOO.util.Event.addListener(document, click, animate);}YAHOO.util.Event.addListener(window, load, YAHOO.example.anim.init);</script></head><body><h1>Animation Example - Basic</h1><p>This example demonstrates how to animate an elements width to a given value.</p><p>Click anywhere to start animation.</p><div id="anim">Lorem ipsum dolor</div></body></html> Designing and Building with Ajax 134
  135. 135. Trigger Operation UpdateLearning Ajax• Learning Ajax, means understanding• Triggers (event or timer)• Operations (ajax xhr)• Updating (dom) Triggering Using XHR Events & for Ajax Updating Timers Operations the DOM Designing and Building with Ajax 135
  136. 136. Summary Designing and Building with Ajax 136
  137. 137. Trigger Operation UpdateAjax Architecture• The Ajax DNA (events, data, presentation) is just a restatement of Model-View-Controller software pattern• It is an architectural approach that separates these three concerns• Model: keep it pure, avoid presentation artifacts• View: keep HTML clear of style. Keep style in CSS.• Controller: don’t mix events in HTML markup, use observer style of event management Designing and Building with Ajax 137
  138. 138. Trigger Operation UpdatePulling It All Together• Two Projects that• Shows XHR in action• Explores XML vs JSON Designing and Building with Ajax 138
  139. 139. Ajax ToolkitsDesigning and Building Ajax Applications with Ajax Toolkits Bill W. Scott, Y! Ajax Evangelist b.scott@yahoo.com
  140. 140. What a Toolkit Provides Designing and Building with Ajax 140
  141. 141. Evaluating Toolkits• What language is it targeted for?• Are you looking for XHR abstraction or high level?• Will you use XML or JSON?• Is it $$ or open source?• Does it simplify general JS development?• Community of support?• Likelihood it will be around next year? Designing and Building with Ajax 141
  142. 142. Ajax Toolkits: Open Source JavaScript LibrariesPrototype Inspired by Ruby, simplifies DOM manipulation, events, Ajax connectivity. Several frameworks based on it. Notable for the $() function among many other shortcuts. OO extends.Scriptaculous Built on Prototype, nice effects, animations, drag and drop, widgets. Nicely documentedRico Built on Prototype, nice effects, animations, behaviours (widgets), drag and drop, nice Ajax engine abstraction, style effects. Lots of demos.Behaviour Built on Prototype, separates event management from HTML using CSS selectorsDojo Widget library, drag and drop, effects, widget framework, event management, animation, bookmarkability, manipulating location history, extensive deployment supportZimbra Extensive set of widgets (data list, wizard, button, rich text editor, tree, menus, etc.). MVC, debugging facilitiesMicrosoft Atlas In developer release. Support for drag and drop, animation, full XML specification for wiring widgets together, behavior abstraction, will be integrated in full suite of MS dev tools.MochiKit Widgets, painless DOM manipulation, task management, JSON-like notation, logging. Active communityYahoo! UI Official Yahoo! DHTML/Ajax library. Contains event mgmt, DOM manipulation, animation, drag and drop, CSS grid, CSS fonts, CSS resets, calendar, tree, autocomplete, windowing, menus, etc. Designing and Building with Ajax 142
  143. 143. Ajax Toolkit: Commercial JavaScript LibrariesTIBCO GI Very extensive framework with full IDE. Dozens of widgets, vector based charting package, support for SOAP. IDE has WYSIWYG GUI layout, step through debugging as well as code completionBindows Been around since 2001, lots of great widgets and library routines. Not always browser independentJackBe Focused at corporate environments. Able to emulate a desktop application. Very fast performance even on a dial-up line. Uses a proprietary “screen” format that gets interpreted by a JavaScript runtime engine.Active Widgets Rich set of JavaScript widgets. Rich grid widget is a high spot. Designing and Building with Ajax 143
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×