SlideShare une entreprise Scribd logo
1  sur  55
Télécharger pour lire hors ligne
JSON and AJAX JumpStart
Scott Good, President
Teamwork Solutions
Columbus / Cincinnati




           ®
Scott Good
 President, Teamwork Solutions
      Columbus, Cincinnati
      2-time Beacon Award Finalists

 Notes Developer/Designer, 15 years

 Extensive workflow and web development experience
      ProcessIt! (2003 E-Pro Apex Award, 2006 & 2007 Advisor Editors’ Choice
      Award winner)

 Have written nearly 50 Lotus Advisor articles
      AJAX
      CSS
      JavaScript
      LotusScript
      Domino web development
Teamwork Solutions…

   Does application development for companies of all sizes
        Abbott Laboratories
        Abercrombie & Fitch
        American Cancer Society
        American Electric Power
        Burger King
        Nationwide Insurance
        Pharmacia Upjohn
        Prudential Insurance
        And many more
Today…
  Introduction to JSON
         What it is
         Why you should care
         Enough to make you (a little) dangerous

  Introduction to AJAX
         What is AJAX?
         How can it be used in Domino apps?
         How to make an AJAX request
         Using JSON as the AJAX data format (instead of XML)
         Putting it into an application
JSON and AJAX…makes you think…
Wrong JSON
 It’s “JSON,” the web technology, not “Jason” the homicidal maniac
    Important safety tip
So, what is JSON?
  JSON = JavaScript Object Notation

  A part of JavaScript many developers don’t know about
     Has been a part of the JavaScript spec since December 1999

  Extends the power of JavaScript arrays

  Can act as a viable (and much easier to use) alternative to XML as
  a data transport
JavaScript Variables
  In JavaScript, variables can contain more or less anything
     Numbers
     Text
     Arrays
     Functions
     Objects
     …in any combination

  You can, for instance, do this:
  var myChild = “Sydney”;
  var age = 14;
  var gender = “female”;
Or, you could use an array
  JavaScript variables don’t have to be single values
     They can contain arrays

  Array elements are identified by position number, starting with zero


  var myChild = [“Sydney”, 14, “female”];
        … so that …
  var sydneyAge = myChild[1];


  Works great…but hard to keep track of what is where
     And hard to read the code
JavaScript Arrays
  Array elements can also be identified by name

  var myChild = []; // identifies myChild as an array
  myChild[“name”] = “Sydney”;
  myChild[“age”] = 14;
  myChild[“gender”] = “female”;

        … so that …

  var sydneyAge = myChild.age;

  Easier to read as code; not much easier to create
JavaScript Arrays
  Named array elements can also be identified in a single statement:

  var myChild = {name: “Sydney”, age: 14, gender: “female”};


        … or, spread out for better readability …

  var myChild = {
        name: “Sydney”,
        age: 14,
        gender: “female”
  };

  Note the braces
JavaScript Arrays
  Functionally, these are the same:

  var myChild = [];
  myChild[“name”] = “Sydney”;
  myChild[“age”] = 14;
  myChild[“gender”] = “female”;

        … is the same as …

  var myChild = {
       name: “Sydney”,
       age: 14,
       gender: “female”
  };
JSON
 But THIS one is considered JSON:

 var myChild = {
      name: “Sydney”,
      age: 14,
      gender: “female”
 };


 Easier to write; easier to read; (better on the resume)
 But, if that was all there was to it, nobody would care
    Fortunately, that’s not all there is to it
JSON = JavaScript Object Notation
  JSON is a extension of JavaScript capabilities

  JSON is a means of describing JavaScript objects which can be filled
  with pretty much anything JavaScript

  As the object model gets more complex, defining the data can get
  more complicated, too

  JSON can help simplify access to the data
Basic JSON Format
  Simple format: An overall object name, then pairs of names and
  values inside braces…

  var objectName = {
         identifier1: value1,
         identifier2: value2,
         identifier3: value3
  }

  Keep in mind, this is JavaScript
      “values” can be pretty much anything, not just simple things like strings
Basic JSON Format
  You will often see the identifiers in quotation marks, too…


  var objectName = {
        “identifier1”: value1,
        “identifier2”: value2,
        “identifier3”: value3
  }


  In my experience, it works either way

  Note where the commas are!
Why bother?...A bit bigger example
  Imagine you have an array of objects you need to track…


  var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];




  Simple enough…you don’t need JSON for that
So, why do this?
  But what if there’s other, related, information you want to track?


  var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];
  var kidsAges = [21, 21, 14, 7];
  var kidsGender = [“female”, “male”, “female”, “female”];



  The data model is starting to get more complex

  Relationships between data are based entirely on array position
Extracting data gets harder
  Find Sydney’s age…

  var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];
  var kidsAges = [21, 21, 14, 7];
  var kidsGender = [“female”, “male”, “female”, “female”];
  for (var x = 0; x < myKids.length; x++){
       if (myKids[x] == “Sydney”){
            var sydneyAge = kidsAges[x];
            break;
       }
  }

  Quite do-able, but fussy…and surprisingly hard for what it is
With JSON, the data model is simpler
  One set of named-pairs can contain others:

  var myKids = {
      Corey: {
          age: 21,
          gender: “female”
      },
      Thaddeus: {age: 21, gender: “male”},
      Sydney: {age: 14, gender: “female”},
      Cameron:{ age: 7, gender: “female”}
  };


  var sydneyAge = myKids.Sydney.age;
Easier to get right, and to read
  Which are you more likely to get right when building the arrays?

  var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];
  var kidsAges = [21, 21, 14, 7];
  var kidsGender = [“female”, “male”, “female”, “female”];

  … or …

  var myKids = {
       Corey: {age: 21, gender: “female”},
       Thaddeus: {age: 21, gender: “male”},
       Sydney: {age: 14, gender: “female”},
       Cameron:{ age: 7, gender: “female”}
  };
Easily extend the data model
  You can easily add more named-pair sets…
  var myKidsAndPets = {
      kids: {
           Corey: {age: 21, gender: “female”},
           Thaddeus: {age: 21, gender: “male”},
           Sydney: {age: 14, gender: “female”},
           Cameron:{ age: 7, gender: “female”}
      },
      pets: {
           Kirby: {type: “dog”, variety: “Labrador Retriever”},
           Spot: {type: “fish”, variety: “Goldfish”}
      }
  };

var sydneyAge = myKidsAndPets.kids.Sydney.age;
Again, consider the alternative…
  MUCH harder to see relationships the “traditional” way…

  var   myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”];
  var   kidsAges = [21, 21, 14, 7];
  var   kidsGender = [“female”, “male”, “female”, “female”];
  var   ourPets = [“Kirby”, “Spot”];
  var   petTypes = [“dog”, “fish”];
  var   petVarieties = [“Labrador Retriever”, “Goldfish”];


  And, it gets worse if the sequence of variable declarations isn’t in a
  totally logical order
JSON: Who Cares?
  You do (or should), particularly if you’re doing things with relatively
  complex data in JavaScript
     Or, if you’re using AJAX

  In AJAX, JSON is an easier approach to doing what you’re probably
  already doing with XML
     MUCH easier
JSON vs XML…why bother with XML?
                                                               <myKidsAndPets>
var myKidsAndPets = {                                            <children>
                                                                    <child>
     kids: {                                                            <name>Corey</name>
        Corey: {age: 21, gender: “female”},                             <age>21</age>
        Thaddeus: {age: 21, gender: “male”},                            <gender>female</gender>
                                                                    </child>
        Sydney: {age: 14, gender: “female”},                        <child>
        Cameron:{ age: 7, gender: “female”}                             <name>Thaddeus</name>
     },                                                                 <age>21</age>
                                                                        <gender>male</gender>
     pets: {                                                        </child>
        Kirby: {type: “dog”, variety: “Labrador Retriever”},        <child>
        Spot: {type: “fish”, variety: “Goldfish”}                       <name>Sydney</name>
                                                                        <age>14</age>
     }                                                                  <gender>female</gender>
   };                                                               </child>
                                                                    <child>
                                                                        <name>Cameron</name>
                                                                        <age>7</age>
                                                                        <gender>female</gender>
                                                                    </child>
                                                                 </children>
                                                                 <pets>
                                                                    <pet>
   JSON is about half the characters (in this                           <name>Kirby</name>
   example), but you also have to parse the                             <type>dog</type>
   XML before you can use it                                            <variety>Labrador Retriever</variety>
                                                                    </pet>
                                                                    <pet>
                                                                    <name>Spot</name>
                                                                        <type>fish</type>
                                                                        <variety>Goldfish</variety>
                                                                    </pet>
                                                                 </pets>
                                                               </myKidsAndPets>
XML vs JSON…mostly the same
  There are some data formats supported by XML not supported by
  JSON (audio, video)
     Unimportant for most of what we do

  JSON is much easier to work with
     Easier to build
     Easier to read
     Easier to parse
     Less data = faster to transport
     And, hey!, less typing

  JSON is a Good Thing…particularly with AJAX
So, how do you use JSON in web apps?
  In JS Header

  In JavaScript libraries

  Computed into on-the-form JavaScript variables
     Using @DbLookup or WebQueryOpen agents

  Or, from Notes Views, along with AJAX…
JSON is now available from Domino views
  Beginning with Domino 7.0.2, you can get JSON from web views

  …/ViewName?ReadViewEntries&OutputFormat=JSON

  Formatting/node names are a LOT like the XML version
Demos
 JSON from a JS Library

 JSON from the JS Header

 JSON from ComputedText

 XML vs JSON from Notes web views
    Compare the node names, structure
BUT…can’t actually get directly to it
  Views return JSON objects, but what are you going to do with
  them?
     Can only get the JSON code with a URL
     NOT as a DbLookup or an embedded view

  CAN use the Notes View JSON in an AJAX call…
What is AJAX?
  Asynchronous JavaScript And XML
     Er…or JSON…or other stuff…

  VERY hot right now (but not new)

  A combination of technologies that have literally transformed
  web applications over the last few years

  Able to work independently of the UI
     That’s the “Asynchronous” part

  Can use XML as the data transport, but doesn’t have to
     Can be JSON
     Or even plain text
Why should you care?
  Can make web applications much…
     Faster
     More intuitive
     Easier to use

  Breaks through a lot of traditional limitations of web
  applications
     Creates a sometimes-link with the server without requiring the UI to refresh




  Demo Google Maps
How can it be used in Domino apps?
   Lets you dynamically retrieve data from the server while the user
   does something else

   Possible uses:
      Check budget availability
      Validate part numbers
      Get sub-category lists from top-category choice
      Look up names from NAB as characters are typed

   The list is limited mostly by your imagination

   NOTE: Older browsers cannot do this (IE prior to 5.5 or so, etc)
How to make an AJAX request
  The basic object, which makes the request, varies depending on
  browser

  MS Internet Explorer (before IE 7.0)
     Uses XMLHTTP ActiveX object
     ajaxReq = new ActiveXObject(“Microsoft.XMLHTTP”);

  Firefox, IE 7.0, etc.
     Use an internal XMLHttpRequest object
     ajaxReq = new XMLHttpRequest();
How to make an AJAX request
  Unless you can be absolutely sure of the browser, you just build for
  both and be done with it

  Determine which is supported by the browser by checking for
  window.ActiveXObject and/or window.XMLHTTPRequest
Building an AJAX request
 function createAJAXRequest(retrievalURL, responseFunction) {
     var ajaxreq;
     if (window.XMLHttpRequest) {
           ajaxReq = new XMLHttpRequest();
     } else if (window.ActiveXObject) {
           ajaxReq = new ActiveXObject(quot;Microsoft.XMLHTTPquot;);
     }
     ajaxReq.open(quot;GETquot;, retrievalURL);
     ajaxReq.onreadystatechange = eval(responseFunction);
     return ajaxReq;
 }
Building an AJAX request
  All this does is set up the process
     Can make requests
     Can receive back XML

  No request has been made (yet)

  It doesn’t know what to do with what it gets back (yet)

  So, we need a little more code…
To actually make the request…
  Need to call the createAJAXRequest() function

  Then, pass in two parameters
     The URL of the view (or other source of JSON) (as a string)
     The name of the function to be run when values come back (as a string)

  Use the send() method to actually make the call


  myAjaxReq = createAJAXRequest(“theURL”, “theFunctionToRun”);
  myAjaxReq.send(null);
What you’ll get back…
  AJAX objects (XMLHttpRequest, etc) return two things:
     responseXML (an object)
     responseText (a string)

  For XML, you’d use ajaxReq.responseXML and work directly with
  the XML DOM in the object

  With JSON, you need to use the string value (as it’s not an XML
  object)
Demo
Make a simple AJAX request from the NAB using a function to do
something with the returned values:


     function processReturnValue(){
        alert(ajaxReq.responseText);
     }
Needs some cleaning up
It works, but the named function is called every time the request
object’s “ready state” changes
   Loading
   Loaded
   Interactive
   Complete

You don’t need to do things on each state change
Check ready state and status to know when to go
HTTP status values:                           ReadyState values:
   404   =   Not found                             0 = uninitialized
   500   =   Internal error                        1 = loading
   100   =   Continue                              2 = loaded
   200   =   Complete (what you want)              3 = interactive
                                                   4 = complete


    function processReturnValue(){
        if (ajaxReq.readyState == 4) {
              if (ajaxReq.status == 200) {
                    alert(ajaxReq.responseText);
              }
        }
    }
Demo
Make a better AJAX request by tweaking the function slightly


      function processReturnValue(){
         if (ajaxReq.readyState == 4){
                if (ajaxReq.state == 200){
                    alert(ajaxReq.responseText);
                }
         }
      }
But this is only text…not JavaScript
  You must convert the responseText to an actual JSON object before
  it will be of any use in your code

   Conversion to a JavaScript object is done using eval()


  var jsonObject = eval(ajaxReq.responseText);

        …or possibly…

  eval(ajaxReq.responseText);
Using eval() to make it live

 function processReturnValue(){
   if (ajaxReq.readyState == 4) {
       if (ajaxReq.status == 200) {
           eval(“viewJSON=” + ajaxReq.responseText);
           var viewRows = viewJSON.viewentry;
           for (var i = 0; i < viewRows.length; i++){
              // looping through the rows…
              docUNID = viewRows[0][“@unid”];
              alert(docUNID);
           }
       }
   }
 }
Demo
 Retrieving JSON from a view, formatting results with HTML
What you have

At this point, all you have are data elements you can easily extract
from the JSON and surround with HTML

But, what more do you need?

With HTML you have…
   JavaScript
   DHTML
   CSS
   And so on

You have retrieved data from another place, asynchronously, and made
it available to whatever you’re doing
Carrying it a bit further

Without a lot of additional work, this could become any number of
things:
   Entry validation
   NAB picker (demo)
   Type-ahead (demo)
   Or something else

It’s powerful technology and not all that hard to do
Where all can you get JSON from Domino?
  Notes Views
     Using ?ReadViewEntries&OutputFormat=JSON

  Notes Views
     Custom JSON objects

  Notes Pages
  Notes Agents
  JavaScript Libraries
  JS Header
  Computed Text or field in the form
Demos…
 AJAX & JSON from a custom view

 AJAX & JSON from a Page

 AJAX & JSON from an Agent
In summary
  Both AJAX and JSON are technologies you should know

  Both make web development easier, web applications more
  powerful

  TOGETHER they are even better

  The more comfortable you are with them, the more places you’ll
  find to use them…and the better your apps will be
Legal Disclaimers
  The workshops, sessions and materials have been prepared by IBM or the session speakers and reflect their own
  views. They are provided for informational purposes only, and are neither intended to, nor shall have the effect
  of being, legal or other guidance or advice to any participant. While efforts were made to verify the
  completeness and accuracy of the information contained in this presentation, it is provided AS IS without
  warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of,
  or otherwise related to, this presentation or any other materials. Nothing contained in this presentation is
  intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or
  licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM
  software.
  References in this presentation to IBM products, programs, or services do not imply that they will be available in
  all countries in which IBM operates. Product release dates and/or capabilities referenced in this presentation may
  change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended
  to be a commitment to future product or feature availability in any way. Nothing contained in these materials is
  intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in
  any specific sales, revenue growth or other results.
  Performance is based on measurements and projections using standard IBM benchmarks in a controlled
  environment. The actual throughput or performance that any user will experience will vary depending upon
  many factors, including considerations such as the amount of multiprogramming in the user's job stream, the I/O
  configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given
  that an individual user will achieve results similar to those stated here.
  All customer examples described are presented as illustrations of how those customers have used IBM products
  and the results they may have achieved. Actual environmental costs and performance characteristics may vary
  by customer.
  IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Sametime, WebSphere, and Lotusphere are trademarks
  of International Business Machines Corporation in the United States, other countries, or both.
  Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other
  countries, or both.
  Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both.
  Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.
  Other company, product, or service names may be trademarks or service marks of others.
Questions?
Thank you!
                       Scott Good: sgood@teamsol.com
                             614-457-7100 x200


                           http://www.teamsol.com
Teamwork Solutions
                       http://www.scottgood.com (blog)



                 PLEASE FILL OUT YOUR EVALUATIONS

Contenu connexe

Plus de dominion

What is a itil and how does it relate to your collaborative environment uklug
What is a itil and how does it relate to your collaborative environment   uklugWhat is a itil and how does it relate to your collaborative environment   uklug
What is a itil and how does it relate to your collaborative environment uklugdominion
 
iOS enterprise
iOS enterpriseiOS enterprise
iOS enterprisedominion
 
cloud session uklug
cloud session uklugcloud session uklug
cloud session uklugdominion
 
Uklug 2011 administrator development synergy
Uklug 2011 administrator development synergyUklug 2011 administrator development synergy
Uklug 2011 administrator development synergydominion
 
Uklug 2011 client management
Uklug 2011 client managementUklug 2011 client management
Uklug 2011 client managementdominion
 
JavaScript blast
JavaScript blastJavaScript blast
JavaScript blastdominion
 
Populating your domino directory or any domino database with tivoli directory...
Populating your domino directory or any domino database with tivoli directory...Populating your domino directory or any domino database with tivoli directory...
Populating your domino directory or any domino database with tivoli directory...dominion
 
Uklug2011 Know your Notes
Uklug2011 Know your NotesUklug2011 Know your Notes
Uklug2011 Know your Notesdominion
 
Taking themes to the next level
Taking themes to the next levelTaking themes to the next level
Taking themes to the next leveldominion
 
Supersize me
Supersize meSupersize me
Supersize medominion
 
Aussie outback
Aussie outbackAussie outback
Aussie outbackdominion
 
Learning to run
Learning to runLearning to run
Learning to rundominion
 
Implementing xpages extension library
Implementing xpages extension libraryImplementing xpages extension library
Implementing xpages extension librarydominion
 
Abb presentation uklug
Abb presentation uklugAbb presentation uklug
Abb presentation uklugdominion
 
Uklug2011.lotus.on.linux.report.technical.edition.v1.0
Uklug2011.lotus.on.linux.report.technical.edition.v1.0Uklug2011.lotus.on.linux.report.technical.edition.v1.0
Uklug2011.lotus.on.linux.report.technical.edition.v1.0dominion
 
Domino testing presentation
Domino testing presentationDomino testing presentation
Domino testing presentationdominion
 
Composite applications tutorial
Composite applications tutorialComposite applications tutorial
Composite applications tutorialdominion
 
Maximizing application performance
Maximizing application performanceMaximizing application performance
Maximizing application performancedominion
 
Error handling in XPages
Error handling in XPagesError handling in XPages
Error handling in XPagesdominion
 

Plus de dominion (20)

What is a itil and how does it relate to your collaborative environment uklug
What is a itil and how does it relate to your collaborative environment   uklugWhat is a itil and how does it relate to your collaborative environment   uklug
What is a itil and how does it relate to your collaborative environment uklug
 
iOS enterprise
iOS enterpriseiOS enterprise
iOS enterprise
 
cloud session uklug
cloud session uklugcloud session uklug
cloud session uklug
 
Uklug 2011 administrator development synergy
Uklug 2011 administrator development synergyUklug 2011 administrator development synergy
Uklug 2011 administrator development synergy
 
Uklug 2011 client management
Uklug 2011 client managementUklug 2011 client management
Uklug 2011 client management
 
JavaScript blast
JavaScript blastJavaScript blast
JavaScript blast
 
Populating your domino directory or any domino database with tivoli directory...
Populating your domino directory or any domino database with tivoli directory...Populating your domino directory or any domino database with tivoli directory...
Populating your domino directory or any domino database with tivoli directory...
 
Uklug2011 Know your Notes
Uklug2011 Know your NotesUklug2011 Know your Notes
Uklug2011 Know your Notes
 
Quickr
QuickrQuickr
Quickr
 
Taking themes to the next level
Taking themes to the next levelTaking themes to the next level
Taking themes to the next level
 
Supersize me
Supersize meSupersize me
Supersize me
 
Aussie outback
Aussie outbackAussie outback
Aussie outback
 
Learning to run
Learning to runLearning to run
Learning to run
 
Implementing xpages extension library
Implementing xpages extension libraryImplementing xpages extension library
Implementing xpages extension library
 
Abb presentation uklug
Abb presentation uklugAbb presentation uklug
Abb presentation uklug
 
Uklug2011.lotus.on.linux.report.technical.edition.v1.0
Uklug2011.lotus.on.linux.report.technical.edition.v1.0Uklug2011.lotus.on.linux.report.technical.edition.v1.0
Uklug2011.lotus.on.linux.report.technical.edition.v1.0
 
Domino testing presentation
Domino testing presentationDomino testing presentation
Domino testing presentation
 
Composite applications tutorial
Composite applications tutorialComposite applications tutorial
Composite applications tutorial
 
Maximizing application performance
Maximizing application performanceMaximizing application performance
Maximizing application performance
 
Error handling in XPages
Error handling in XPagesError handling in XPages
Error handling in XPages
 

Dernier

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 

Dernier (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 

JSON and AJAX JumpStart

  • 1. JSON and AJAX JumpStart Scott Good, President Teamwork Solutions Columbus / Cincinnati ®
  • 2. Scott Good President, Teamwork Solutions Columbus, Cincinnati 2-time Beacon Award Finalists Notes Developer/Designer, 15 years Extensive workflow and web development experience ProcessIt! (2003 E-Pro Apex Award, 2006 & 2007 Advisor Editors’ Choice Award winner) Have written nearly 50 Lotus Advisor articles AJAX CSS JavaScript LotusScript Domino web development
  • 3. Teamwork Solutions… Does application development for companies of all sizes Abbott Laboratories Abercrombie & Fitch American Cancer Society American Electric Power Burger King Nationwide Insurance Pharmacia Upjohn Prudential Insurance And many more
  • 4. Today… Introduction to JSON What it is Why you should care Enough to make you (a little) dangerous Introduction to AJAX What is AJAX? How can it be used in Domino apps? How to make an AJAX request Using JSON as the AJAX data format (instead of XML) Putting it into an application
  • 5. JSON and AJAX…makes you think…
  • 6.
  • 7. Wrong JSON It’s “JSON,” the web technology, not “Jason” the homicidal maniac Important safety tip
  • 8. So, what is JSON? JSON = JavaScript Object Notation A part of JavaScript many developers don’t know about Has been a part of the JavaScript spec since December 1999 Extends the power of JavaScript arrays Can act as a viable (and much easier to use) alternative to XML as a data transport
  • 9. JavaScript Variables In JavaScript, variables can contain more or less anything Numbers Text Arrays Functions Objects …in any combination You can, for instance, do this: var myChild = “Sydney”; var age = 14; var gender = “female”;
  • 10. Or, you could use an array JavaScript variables don’t have to be single values They can contain arrays Array elements are identified by position number, starting with zero var myChild = [“Sydney”, 14, “female”]; … so that … var sydneyAge = myChild[1]; Works great…but hard to keep track of what is where And hard to read the code
  • 11. JavaScript Arrays Array elements can also be identified by name var myChild = []; // identifies myChild as an array myChild[“name”] = “Sydney”; myChild[“age”] = 14; myChild[“gender”] = “female”; … so that … var sydneyAge = myChild.age; Easier to read as code; not much easier to create
  • 12. JavaScript Arrays Named array elements can also be identified in a single statement: var myChild = {name: “Sydney”, age: 14, gender: “female”}; … or, spread out for better readability … var myChild = { name: “Sydney”, age: 14, gender: “female” }; Note the braces
  • 13. JavaScript Arrays Functionally, these are the same: var myChild = []; myChild[“name”] = “Sydney”; myChild[“age”] = 14; myChild[“gender”] = “female”; … is the same as … var myChild = { name: “Sydney”, age: 14, gender: “female” };
  • 14. JSON But THIS one is considered JSON: var myChild = { name: “Sydney”, age: 14, gender: “female” }; Easier to write; easier to read; (better on the resume) But, if that was all there was to it, nobody would care Fortunately, that’s not all there is to it
  • 15. JSON = JavaScript Object Notation JSON is a extension of JavaScript capabilities JSON is a means of describing JavaScript objects which can be filled with pretty much anything JavaScript As the object model gets more complex, defining the data can get more complicated, too JSON can help simplify access to the data
  • 16. Basic JSON Format Simple format: An overall object name, then pairs of names and values inside braces… var objectName = { identifier1: value1, identifier2: value2, identifier3: value3 } Keep in mind, this is JavaScript “values” can be pretty much anything, not just simple things like strings
  • 17. Basic JSON Format You will often see the identifiers in quotation marks, too… var objectName = { “identifier1”: value1, “identifier2”: value2, “identifier3”: value3 } In my experience, it works either way Note where the commas are!
  • 18. Why bother?...A bit bigger example Imagine you have an array of objects you need to track… var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”]; Simple enough…you don’t need JSON for that
  • 19. So, why do this? But what if there’s other, related, information you want to track? var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”]; var kidsAges = [21, 21, 14, 7]; var kidsGender = [“female”, “male”, “female”, “female”]; The data model is starting to get more complex Relationships between data are based entirely on array position
  • 20. Extracting data gets harder Find Sydney’s age… var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”]; var kidsAges = [21, 21, 14, 7]; var kidsGender = [“female”, “male”, “female”, “female”]; for (var x = 0; x < myKids.length; x++){ if (myKids[x] == “Sydney”){ var sydneyAge = kidsAges[x]; break; } } Quite do-able, but fussy…and surprisingly hard for what it is
  • 21. With JSON, the data model is simpler One set of named-pairs can contain others: var myKids = { Corey: { age: 21, gender: “female” }, Thaddeus: {age: 21, gender: “male”}, Sydney: {age: 14, gender: “female”}, Cameron:{ age: 7, gender: “female”} }; var sydneyAge = myKids.Sydney.age;
  • 22. Easier to get right, and to read Which are you more likely to get right when building the arrays? var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”]; var kidsAges = [21, 21, 14, 7]; var kidsGender = [“female”, “male”, “female”, “female”]; … or … var myKids = { Corey: {age: 21, gender: “female”}, Thaddeus: {age: 21, gender: “male”}, Sydney: {age: 14, gender: “female”}, Cameron:{ age: 7, gender: “female”} };
  • 23. Easily extend the data model You can easily add more named-pair sets… var myKidsAndPets = { kids: { Corey: {age: 21, gender: “female”}, Thaddeus: {age: 21, gender: “male”}, Sydney: {age: 14, gender: “female”}, Cameron:{ age: 7, gender: “female”} }, pets: { Kirby: {type: “dog”, variety: “Labrador Retriever”}, Spot: {type: “fish”, variety: “Goldfish”} } }; var sydneyAge = myKidsAndPets.kids.Sydney.age;
  • 24. Again, consider the alternative… MUCH harder to see relationships the “traditional” way… var myKids = [“Corey”, “Thaddeus”, “Sydney”, “Cameron”]; var kidsAges = [21, 21, 14, 7]; var kidsGender = [“female”, “male”, “female”, “female”]; var ourPets = [“Kirby”, “Spot”]; var petTypes = [“dog”, “fish”]; var petVarieties = [“Labrador Retriever”, “Goldfish”]; And, it gets worse if the sequence of variable declarations isn’t in a totally logical order
  • 25. JSON: Who Cares? You do (or should), particularly if you’re doing things with relatively complex data in JavaScript Or, if you’re using AJAX In AJAX, JSON is an easier approach to doing what you’re probably already doing with XML MUCH easier
  • 26. JSON vs XML…why bother with XML? <myKidsAndPets> var myKidsAndPets = { <children> <child> kids: { <name>Corey</name> Corey: {age: 21, gender: “female”}, <age>21</age> Thaddeus: {age: 21, gender: “male”}, <gender>female</gender> </child> Sydney: {age: 14, gender: “female”}, <child> Cameron:{ age: 7, gender: “female”} <name>Thaddeus</name> }, <age>21</age> <gender>male</gender> pets: { </child> Kirby: {type: “dog”, variety: “Labrador Retriever”}, <child> Spot: {type: “fish”, variety: “Goldfish”} <name>Sydney</name> <age>14</age> } <gender>female</gender> }; </child> <child> <name>Cameron</name> <age>7</age> <gender>female</gender> </child> </children> <pets> <pet> JSON is about half the characters (in this <name>Kirby</name> example), but you also have to parse the <type>dog</type> XML before you can use it <variety>Labrador Retriever</variety> </pet> <pet> <name>Spot</name> <type>fish</type> <variety>Goldfish</variety> </pet> </pets> </myKidsAndPets>
  • 27. XML vs JSON…mostly the same There are some data formats supported by XML not supported by JSON (audio, video) Unimportant for most of what we do JSON is much easier to work with Easier to build Easier to read Easier to parse Less data = faster to transport And, hey!, less typing JSON is a Good Thing…particularly with AJAX
  • 28. So, how do you use JSON in web apps? In JS Header In JavaScript libraries Computed into on-the-form JavaScript variables Using @DbLookup or WebQueryOpen agents Or, from Notes Views, along with AJAX…
  • 29. JSON is now available from Domino views Beginning with Domino 7.0.2, you can get JSON from web views …/ViewName?ReadViewEntries&OutputFormat=JSON Formatting/node names are a LOT like the XML version
  • 30. Demos JSON from a JS Library JSON from the JS Header JSON from ComputedText XML vs JSON from Notes web views Compare the node names, structure
  • 31. BUT…can’t actually get directly to it Views return JSON objects, but what are you going to do with them? Can only get the JSON code with a URL NOT as a DbLookup or an embedded view CAN use the Notes View JSON in an AJAX call…
  • 32. What is AJAX? Asynchronous JavaScript And XML Er…or JSON…or other stuff… VERY hot right now (but not new) A combination of technologies that have literally transformed web applications over the last few years Able to work independently of the UI That’s the “Asynchronous” part Can use XML as the data transport, but doesn’t have to Can be JSON Or even plain text
  • 33. Why should you care? Can make web applications much… Faster More intuitive Easier to use Breaks through a lot of traditional limitations of web applications Creates a sometimes-link with the server without requiring the UI to refresh Demo Google Maps
  • 34. How can it be used in Domino apps? Lets you dynamically retrieve data from the server while the user does something else Possible uses: Check budget availability Validate part numbers Get sub-category lists from top-category choice Look up names from NAB as characters are typed The list is limited mostly by your imagination NOTE: Older browsers cannot do this (IE prior to 5.5 or so, etc)
  • 35. How to make an AJAX request The basic object, which makes the request, varies depending on browser MS Internet Explorer (before IE 7.0) Uses XMLHTTP ActiveX object ajaxReq = new ActiveXObject(“Microsoft.XMLHTTP”); Firefox, IE 7.0, etc. Use an internal XMLHttpRequest object ajaxReq = new XMLHttpRequest();
  • 36. How to make an AJAX request Unless you can be absolutely sure of the browser, you just build for both and be done with it Determine which is supported by the browser by checking for window.ActiveXObject and/or window.XMLHTTPRequest
  • 37. Building an AJAX request function createAJAXRequest(retrievalURL, responseFunction) { var ajaxreq; if (window.XMLHttpRequest) { ajaxReq = new XMLHttpRequest(); } else if (window.ActiveXObject) { ajaxReq = new ActiveXObject(quot;Microsoft.XMLHTTPquot;); } ajaxReq.open(quot;GETquot;, retrievalURL); ajaxReq.onreadystatechange = eval(responseFunction); return ajaxReq; }
  • 38. Building an AJAX request All this does is set up the process Can make requests Can receive back XML No request has been made (yet) It doesn’t know what to do with what it gets back (yet) So, we need a little more code…
  • 39. To actually make the request… Need to call the createAJAXRequest() function Then, pass in two parameters The URL of the view (or other source of JSON) (as a string) The name of the function to be run when values come back (as a string) Use the send() method to actually make the call myAjaxReq = createAJAXRequest(“theURL”, “theFunctionToRun”); myAjaxReq.send(null);
  • 40. What you’ll get back… AJAX objects (XMLHttpRequest, etc) return two things: responseXML (an object) responseText (a string) For XML, you’d use ajaxReq.responseXML and work directly with the XML DOM in the object With JSON, you need to use the string value (as it’s not an XML object)
  • 41. Demo Make a simple AJAX request from the NAB using a function to do something with the returned values: function processReturnValue(){ alert(ajaxReq.responseText); }
  • 42. Needs some cleaning up It works, but the named function is called every time the request object’s “ready state” changes Loading Loaded Interactive Complete You don’t need to do things on each state change
  • 43. Check ready state and status to know when to go HTTP status values: ReadyState values: 404 = Not found 0 = uninitialized 500 = Internal error 1 = loading 100 = Continue 2 = loaded 200 = Complete (what you want) 3 = interactive 4 = complete function processReturnValue(){ if (ajaxReq.readyState == 4) { if (ajaxReq.status == 200) { alert(ajaxReq.responseText); } } }
  • 44. Demo Make a better AJAX request by tweaking the function slightly function processReturnValue(){ if (ajaxReq.readyState == 4){ if (ajaxReq.state == 200){ alert(ajaxReq.responseText); } } }
  • 45. But this is only text…not JavaScript You must convert the responseText to an actual JSON object before it will be of any use in your code Conversion to a JavaScript object is done using eval() var jsonObject = eval(ajaxReq.responseText); …or possibly… eval(ajaxReq.responseText);
  • 46. Using eval() to make it live function processReturnValue(){ if (ajaxReq.readyState == 4) { if (ajaxReq.status == 200) { eval(“viewJSON=” + ajaxReq.responseText); var viewRows = viewJSON.viewentry; for (var i = 0; i < viewRows.length; i++){ // looping through the rows… docUNID = viewRows[0][“@unid”]; alert(docUNID); } } } }
  • 47. Demo Retrieving JSON from a view, formatting results with HTML
  • 48. What you have At this point, all you have are data elements you can easily extract from the JSON and surround with HTML But, what more do you need? With HTML you have… JavaScript DHTML CSS And so on You have retrieved data from another place, asynchronously, and made it available to whatever you’re doing
  • 49. Carrying it a bit further Without a lot of additional work, this could become any number of things: Entry validation NAB picker (demo) Type-ahead (demo) Or something else It’s powerful technology and not all that hard to do
  • 50. Where all can you get JSON from Domino? Notes Views Using ?ReadViewEntries&OutputFormat=JSON Notes Views Custom JSON objects Notes Pages Notes Agents JavaScript Libraries JS Header Computed Text or field in the form
  • 51. Demos… AJAX & JSON from a custom view AJAX & JSON from a Page AJAX & JSON from an Agent
  • 52. In summary Both AJAX and JSON are technologies you should know Both make web development easier, web applications more powerful TOGETHER they are even better The more comfortable you are with them, the more places you’ll find to use them…and the better your apps will be
  • 53. Legal Disclaimers The workshops, sessions and materials have been prepared by IBM or the session speakers and reflect their own views. They are provided for informational purposes only, and are neither intended to, nor shall have the effect of being, legal or other guidance or advice to any participant. While efforts were made to verify the completeness and accuracy of the information contained in this presentation, it is provided AS IS without warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this presentation or any other materials. Nothing contained in this presentation is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software. References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates. Product release dates and/or capabilities referenced in this presentation may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results. Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon many factors, including considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve results similar to those stated here. All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer. IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Sametime, WebSphere, and Lotusphere are trademarks of International Business Machines Corporation in the United States, other countries, or both. Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both. Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both. Other company, product, or service names may be trademarks or service marks of others.
  • 55. Thank you! Scott Good: sgood@teamsol.com 614-457-7100 x200 http://www.teamsol.com Teamwork Solutions http://www.scottgood.com (blog) PLEASE FILL OUT YOUR EVALUATIONS