Friday, August 30, 2013

Simple JSON Example

Simple JSON example

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
body{
    font-size: 12px; font-family: sans-serif;
}
</style>
</head>

<body>

<h3>Employee Details</h3>
<p>First Name: <span id="fname"></span></p>
<p>Last Name: <span id="lname"></span></p>
<p>Age: <span id="age"></span></p>
<h3>Address</h3>
<p>Address : <span id="address1"></span></p>
<p>Street : <span id="address2"></span></p>
<p>City : <span id="city"></span></p>
<p>Country : <span id="country"></span></p>
<h3>Department Information</h3>
<p>Department Name : <span id="deptname"></span></p>
<p>Job Role : <span id="jrole"></span></p>
<p>Designation : <span id="desig"></span></p>

<script>
var employees = [
{ "firstName" : "Sanjeeva" , "lastName" : "Pathirana" , "age" : 30 },
{ "firstName" : "Sandamali" , "lastName" : "Silva" , "age" : 25 },
{ "firstName" : "Thinuli" , "lastName" : "Pathirana" , "age" : 20 }];

document.getElementById("fname").innerHTML= employees[0].firstName;
document.getElementById("lname").innerHTML= employees[0].lastName;
document.getElementById("age").innerHTML= employees[0].age;

var addressVar = '{"address":[' +
'{"add1":"126 B","add2":"Pubudu Uyana", "city" : "Piliyandala" , "country" : "Sri Lanka" }' +
']}';

var addressObj = eval ("(" + addressVar + ")");

document.getElementById("address1").innerHTML=addressObj.address[0].add1;
document.getElementById("address2").innerHTML=addressObj.address[0].add2;
document.getElementById("city").innerHTML=addressObj.address[0].city;
document.getElementById("country").innerHTML=addressObj.address[0].country;

var JSONObject = {
     "department":"Information Technology",
     "role":"Team Lead",
     "designation":"Software Engineer"
};
document.getElementById("deptname").innerHTML=JSONObject.department;
document.getElementById("jrole").innerHTML=JSONObject.role;
document.getElementById("desig").innerHTML=JSONObject.designation ;
</script>

</body>
</html>

Out put as follows :

JSON – Introduction


JSON – Introduction

JSON – JavaScript Object Notation

* JSON is lightweight text-data interchange format
* JSON is language independent
* JSON is smaller than XML, and faster and easier to parse.

{ “students” : [ {“name”:”sanjeeva”, “department”:”CSE”},{“name”:”chandima”, “department”:”IT”} ] }

* JSON - Evaluates to JavaScript Objects
The JSON text format is syntactically identical to the code for creating JavaScript objects., therefore without using a parser, can use the a JavaScript built-in eval() function to execute JSON data.

Like XML ,
* JSON is plain text
* JSON is "self-describing" (human readable)
* JSON is hierarchical (values within values)
* JSON can be parsed by JavaScript
* JSON data can be transported using AJAX

Unlike XML ,
* No end tag
* Shorter
* Quicker to read and write
* Can be parsed using built-in JavaScript eval()
* Uses arrays
* No reserved words

JSON Syntax Rules -

JSON syntax is a subset of the JavaScript object notation syntax:
* Data is in name/value pairs
* Data is separated by commas
* Curly braces hold objects
* Square brackets hold arrays

JSON Name/Value Pairs

name (field name) / value pair : "firstName" : "Sanjeeva"
JSON values can be:
* A number (integer or floating point)
* A string (in double quotes)
* A Boolean (true or false)
* An array (in square brackets)
* An object (in curly brackets)
* null 

JSON Objects
* JSON objects are written inside curly brackets,
* Objects can contain multiple name/values pairs:
{ "firstName":"Sanjeeva" , "lastName":"Pathirana", “age”:30 }


JSON Arrays
JSON arrays are written inside square brackets.
An array can contain multiple objects:
{
"employees": [
        { "firstName":"Sanjeeva" , "lastName":"Pathirana" },
        { "firstName":"Sandamali" , "lastName":"Silva" },
        { "firstName":"Thinuli" , "lastName":"Pathirana" }
    ]
}
In the example above, the object "employees" is an array containing three objects. Each object is a record with a first name and a last name.

JSON Files
* The file type for JSON files is ".json"
* The MIME type for JSON text is "application/json"

Converting a JSON Text to a JavaScript Object

One of the most common use of JSON is to fetch JSON data from a web server (as a file or as an HttpRequest), convert the JSON data to a JavaScript object, and then it uses the data in a web page.

JSON Parser 

The eval() function can compile and execute any JavaScript. This represents a potential security problem.
It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser will recognize only JSON text and will not compile scripts.

AJAX Basic Callback Example


AJAX Basic Callback Example

Here is a basic AJAX example which write to demonstrate the callback function call.

Out put -



Once click the “Answer” button the AJAX response as follow.

  
Once click the “Example” button the AJAX response as follow.




Below are the steps for the above example.

1. AjaxBasicCallBack.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX Basic</title>
<style type="text/css">@IMPORT url("css/AjaxBasic.css");</style>
<script>

var xmlhttp;
function loadXMLDoc(url,cfunc)
{
     if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{ // code for IE5, IE6
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
     xmlhttp.onreadystatechange=cfunc;
     xmlhttp.open("GET",url,true);
     xmlhttp.send();
}

function func_myAnswer()
{
     loadXMLDoc("resource/AjaxText.txt",function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("AJAXAnswerDiv").innerHTML=xmlhttp.responseText;
        }
    });
}

function func_myExample()
{
      var txt,x,i;
      loadXMLDoc("resource/ajaxCatlog.xml",function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                 xmlDoc = xmlhttp.responseXML;
                 txt="";
                 x=xmlDoc.getElementsByTagName("examples");
                 for (i=0;i<x.length;i++){
                      txt=txt + x[i].childNodes[0].nodeValue + "<br>";
                 }
                 document.getElementById("AJAXExampleDiv").innerHTML=txt;
            }
     });
}
</script>
</head>
<body>
<h2>AJAX → Asynchronous JavaScript and XML</h2>
<p>* AJAX is a mechanism of exchanging data with a server, and updating parts of a web page, without reloading the whole page.</p>
<p>* What is AJAX ?</p>
<div id="AJAXAnswerDiv" class="redfont"></div>
<p>* What are the examples AJAX using applications ?</p>
<div id="AJAXExampleDiv" class="bluefont"></div>
<br>
<button onclick="func_myAnswer()">Answer</button>
<button onclick="func_myExample()">Example</button>
</body>
</html>

2. AjaxBasic.css

@CHARSET "UTF-8";

body{
font-size: 12px;
font-family: sans-serif;
}
.redfont{
color: red;
}
.bluefont{
color: blue;
}
.h1Gray{
color: gray;
}

3. ajaxCatlog.xml

<?xml version="1.0"?>
<ajaxexamples>
<examples>Goolge Maps</examples>
<examples>Gmail</examples>
<examples>Youtube</examples>
</ajaxexamples>

4. AjaxText.txt

<p class="redfont">AJAX is a technique for creating fast and dynamic web pages</p>





 

AJAX Basic Example – responseXML


AJAX Basic Example – responseXML

Here is a basic AJAX example which write to demonstrate get the response by XML.

Out put -

Once click the “Example” button the AJAX response as follow.



Below are the steps for the above example.

1. AjaxBasicResponseText.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX Basic - ResponseXML</title>
<style type="text/css">@IMPORT url("css/AjaxBasic.css");</style>
<script>
function loadXMLDoc()
{
var xmlhttp;
var txt,x,i;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
xmlDoc = xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("examples");
for (i=0;i<x.length;i++){
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("AJAXExampleDiv").innerHTML=txt;
}
}
xmlhttp.open("GET","resource/ajaxCatlog.xml",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX → Asynchronous JavaScript and XML</h2>
<p>* AJAX is a mechanism of exchanging data with a server, and updating parts of a web page, without reloading the whole page.</p>
<p>* What is AJAX ?.</p>
<p class="redfont">AJAX is a technique for creating fast and dynamic web pages</p>
Examples of applications using AJAX:<br>
<div id="AJAXExampleDiv" class="bluefont"></div>
<br>
<button onclick="loadXMLDoc()">Example</button>

</body>
</html>

2. AjaxBasic.css

@CHARSET "UTF-8";

body{
font-size: 12px;
font-family: sans-serif;
}
.redfont{
color: red;
}
.bluefont{
color: blue;
}
.h1Gray{
color: gray;
}

3. ajaxCatlog.xml

<?xml version="1.0"?>
<ajaxexamples>
<examples>Goolge Maps</examples>
<examples>Gmail</examples>
<examples>Youtube</examples>
</ajaxexamples>