The document provides an introduction to JSON and AJAX. It discusses what JSON is, how it can be used to structure data in JavaScript objects, and why it is easier to work with than XML. It then covers what AJAX is and how it can be used to asynchronously retrieve and update data in web applications without reloading the page. Examples are given of how JSON and AJAX can be implemented in Domino applications by retrieving JSON from views via URLs or making AJAX requests to dynamically load and validate data.
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
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);
}
}
}
}
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