Monday, 22 July 2013

HTTP Adapters with REST/JSON Services

Using IBM Worklight HTTP Adapters with REST/JSON Services 

Abstract

The IBM Worklight Server provides 'adapters' which can issue requests to web services, databases, and other applications on behalf of mobile device applications.  Adapters can be used to combine information from multiple sources into single responses to mobile devices.  They can also modify data before the request and after the response using server-side javascript, and can even be used to cache freq
uently-requested data.

This introductory tutorial explains how to create and use an HTTP Adapter and mobile application to fetch data from a web service which returns data in JSON format.


Introduction

I recently started using IBM Worklight to build mobile apps.  I needed to write an app which fetches information from a REST service, where the data is returned in JSON format.  I chose to use a server-side HTTP adapter to issue the request, in anticipation of future requirements to fetch additional data from other sources.

To figure out the secrets, I wrote an HTTP adapter which submits an address to the Google Geocoding Service.  This public service returns the latitude and longitude coordinate values (along with a lot of other information) for the address specified in the request.  After the adapter was working on the server, I enhanced my HelloWorklight mobile app to request coordinates for several address locations from the HTTP adapter.
 
 
Architecture

Figure 1 shows a high-level view of the traffic flow.  (a) The mobile app issues a request to the HTTP Adapter which runs in the Worklight Server.  (b) The adapter sends the web request to the backend web service.   (c) The web service returns a response in JSON format to the adapter.   (d) Finally, the adapter returns the response in JSON format to the mobile app.
 
image 

References

The IBM Worklight website has a lot of good tutorials.  I learned everything I needed for this exercise from several tutorials in the section named 'Server-Side Development':

http://www-01.ibm.com/software/mobile-solutions/worklight/library/

The Google Geocoding Service is simple to use.  Requests are of the form: 
    http://maps.googleapis.com/maps/api/geocode/json?address=100 Broadway, New York, NY&sensor=false   
Responses contain a large JSON structure which includes latitude and longitude values.  Complete documentation is here:

https://developers.google.com/maps/documentation/geocoding/


Prereqs

I first set up IBM Worklight in Eclipse on my laptop, created the HelloWorklight project according to the initial tutorials, and installed the resulting APK on my Android mobile phone.  I followed the tutorials in the first two sections here  http://www-01.ibm.com/software/mobile-solutions/worklight/library/  to set up the basic development environment and the Android development environment.


Step 1 of 4. Create a basic HTTP adapter to fetch JSON data from a web service

Start Eclipse.

Right-click HelloWorklightProject-> New-> Worklight Adapter
    Project name:  HelloWorklightProject
    Adapter type:  HTTP Adapter
    Adapter name:  myRESTAdapter

This created several subdirectories and files.

I expanded and edited file HelloWorklightProject-> adapters-> myRESTAdapter-> myRESTAdapter.xml

I changed the 'domain' statement to point to the Google Geocoding Service site:

<domain>maps.googleapis.com</domain>

I listed one procedure.  The term 'procedure' refers to a javascript method in myRESTAdapter-impl.js

<procedure name="getGmapLatLng"/>

I expanded and edited file HelloWorklightProject-> adapters-> myRESTAdapter-> myRESTAdapter-impl.js

I deleted everything in the file and I wrote one small new function.  The function creates an object named 'input' and calls the Worklight Server method invokeHttp().  The path variable was set to point to the Google Geocoding Service:  maps/api/geocode/json'.   The variable 'returnedContentType' was set to 'json', since that is the expected response format from the Google Geocoding Service.  The function accepts an address string as input, which is passed to the Google Geocoding Service as a query parameter.  For example, 'address=100 Broadway, New York, NY'.  A second required parameter is also hard-coded and passed along: 'sensor=false'.

In this initial coding, the method returned the entire large JSON response object, as received from the Google Geocoding Service.

function getGmapLatLng(pAddress) {

    var input = {
        method : 'get',
        returnedContentType : 'json',
        path : 'maps/api/geocode/json',
        parameters : {
            'address' : pAddress,
            'sensor' : 'false'   // hard-coded
        }
    };
  
    return WL.Server.invokeHttp(input);
}

That's it.  Coding of the initial HTTP Adapter is now complete.  It's time to test.


Step 2 of 4. Test the HTTP adapter within Eclipse

IBM Worklight provides a neat ability to test the javascript functions in adapter directly from Eclipse.  Input parameters can be specified manually, simulating values which will eventually be provided by a mobile app.  This lets us debug the adapter in a small environment.

I tested the adapter by expanding HelloWorklightProject-> adapters.   Right-click myRestAdapter-> Run As-> Invoke Worklight Procedure

image

I selected my project, adapter, and javascript method, I typed a physical address (between quotes) in the parameter box, then clicked 'Run'.

image

After a little debugging, I finally got a successful response.  The Worklight 'Invoke Procedure Result' window shows the entire JSON structure returned by the Google API.  It can be scrolled up and down to see more values, including the latitude and longitude I wanted.

image


Success.  This proved that I could issue a request to the web service and get a usable response.


Step 3 of 4. Modify the response data using server-side javascript within the HTTP Adapter

My next step was to extract the latitude and longitude values from the JSON response structure.   The JSON response is huge, and I did not want to send it all to my mobile app.

Aside: For trendy buzzword aficiandos, processing at this point in the overall flow is called 'server-side javascript' processing...

I added some additional javascript in myRESTAdapter-impl.js to drill down into the response JSON and extract the latitude and longitude values:


    // Extract latitude and longitude from the response.
    var type = typeof response
    if ("object" == type) {
        if (true == response["isSuccessful"]) {
          
            // Drill down into the response object.
            var results = response["results"];
            var result = results[0];
            var geometry = result["geometry"];
            var location = geometry["location"];
          
            // Return JSON object with lat and lng.
            return location;
        }
        else {
            // Returning null. Web request was not successful.
            return null;
        }
    }
    else {
        // Returning null. Response is not an object.
        return null;
    }

Repeating the test again showed that the code now returned only the latitude and longitude values, along with a boolean 'isSuccessful'.

image 

The HTTP adapter running on the Worklight server is now ready to be used by a mobile app.


Step 4 of 4. Enhance the HelloWorklight mobile app to fetch the JSON data from the HTTP adapter

I added new functionality to the HelloWorklight mobile app which I had developed previously.   I put everything in the HTML file for convenience.   Here is the code:

In the body section, I added HTML for several buttons.  They list addresses in cities around the world.  The buttons all call one javascript method mobGmapLatLng() in the mobile app.

        Hello Worklight with getGmapLatLng
        <p>
        <button onclick="mobGmapLatLng( '11501 Burnet Rd, Austin, TX, USA' )">Austin, TX, USA</button>
        <p>
        <button onclick="mobGmapLatLng( '4250 South Miami Boulevard, Durham, NC, USA' )">Durham, NC, USA</button>
        <p>
        <button onclick="mobGmapLatLng( '1681 Route des Dolines, 06560 Valbonne, France' )">Valbonne, France</button>
        <p>
        <button onclick="mobGmapLatLng( 'Shefayim 60990, Israel' )">Shefayim, Israel</button>
        <p>
        <button onclick="mobGmapLatLng( '399 Ke Yuan Lu, Shanghai, China' )">Shanghai, China</button>
      

In the head section, I added a new javascript function mobGmapLatLng.  This method invokes the Worklight Client API function 'invokeProcedure()' on the mobile device.  This function calls into the Worklight Server, and connects the request to my javascript method getGmapLatLng() in the HTTP Adapter.   I specified the name of the adapter, name of the function (aka procedure), and the address parameter in object 'invocationData':

                function mobGmapLatLng(pAddress) {
                    var invocationData = {
                            adapter : 'myRESTAdapter',
                            procedure : 'getGmapLatLng',
                            parameters : [ pAddress ]
                        };
  
                    WL.Client.invokeProcedure(invocationData,{
                        onSuccess : mobGmapLatLngSuccess,
                        onFailure : mobGmapLatLngFailure,
                    });
                }

I also added two methods, one to handle a successful response, the other to handle a failed response.

The success handler parses the JSON response object from the HTTP adapter, and displays it to the user in an alert.

                function mobGmapLatLngSuccess(result) {
                    var httpStatusCode = result.status;
                    if (200 == httpStatusCode) {
                        var invocationResult = result.invocationResult;
                        var isSuccessful = invocationResult.isSuccessful;
                        if (true == isSuccessful) {
                            var lat = invocationResult.lat;
                            var lng = invocationResult.lng;
                            alert("Success: lat=" + lat + " lng=" + lng);
                        }
                        else {
                            alert("Error. isSuccessful=" + isSuccessful);
                        }                  
                    }
                    else {
                        alert("Error. httpStatusCode=" + httpStatusCode);
                    }
                }


The failure handler did not do much in this exercise.  A production function would obviously need more error-handling here.

                function mobGmapLatLngFailure(result){
                    alert("mobGmapLatLngFailure");
                }


After rebuilding and redeploying the app to my mobile device, I clicked the button for Valbonne, France.  The request propagated through the HTTP adapter on the Worklight Server, to the Google Geocoding Service, back to the adapter, and back to my device.  The javascript in my mobile app javascript parsed the response and popped up this simple alert:

image

As a final verification, I typed the latitude and longitude values into Google Maps.  It showed the correct location for Valbonne, France.  The other cities worked too.  Success!

image


Conclusion

This article shared the secrets of creating, testing, and using an IBM Worklight HTTP adapter with a mobile app to fetch data from a REST web service which returns the response in JSON format.

These techniques provide the foundation for writing server-side code to issue requests to multiple information sources such as web services, databases, even other apps within the same server, perhaps caching the most frequently requested information, and then returning all the data back to the mobile device in one response.

Sunday, 21 July 2013

Call a JSON Web Service

This article demonstrates how to consume the Airport Service of the Federal Aviation Administration using the standard Android HTTP client API and the standard Android JSON parser. The FAA offers a tutorial describing their web services.

While this article includes code snippets only, the full code sample is included in dot42 update 1.0.0.61 or higher. See folder [MyDocuments]\dot42\Samples\Various\AirportInfo.

Send a GET request to the Airport Service

To get the airport status for airport OAK, including known delays and weather data, you would make a GET request to the following URL:

http://services.faa.gov/airport/status/OAK?format=application/json

The above URL encodes two input arguments: First, the three letter airport code (in this case OAK). Second, the format of the data that you would like to get back (in this case JSON).

The following code makes this request:
string iataCode = "OAK";
var uri = string.Format("http://services.faa.gov/airport/status/{0}?format=application/json", iataCode);
var client = AndroidHttpClient.NewInstance("AirportInfo");
var request = new HttpGet(uri);
var response = client.Execute(request); // send the request

Parse the HTTP response

When the above request is made to the service, it will return a response consisting of plain text formatted according the JSON format. Android offers class JSONObject to parse the name/value pairs.

First, we must extract the JSON string from the response:
var content = response.GetEntity().GetContent();
var reader = new BufferedReader(new InputStreamReader(content));
var builder = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
  builder.Append(line);
}
string jsonString = builder.ToString();
Then we wrap a JSONObject around the string:
JSONObject json = new JSONObject(jsonString);
And now we can query named values like this:
string state= json.GetString("state");
string city = json.GetString("city");

The full code


The full code sample is included in dot42 update 1.0.0.61 or higher. See folder [MyDocuments]\dot42\Samples\Various\AirportInfo.

Saturday, 20 July 2013

JSON Tutorial

JSON or JavaScript Object Notation is a lightweight is a text-based open standard designed for human-readable data interchange. The JSON format was originally specified by Douglas Crockford, and is described in RFC 4627. The official Internet media type for JSON is application/json. The JSON filename extension is .json.
This tutorial will help you in understanding JSON and how to use it within various programming languages like PHP, PERL, Python, Ruby, Java etc.
This tutorial has been designed to help beginners understand basic functionality of JavaScript Object Notation (JSON) to develop data interchange format. After completing this tutorial you will find yourself at a moderate level of expertise in using JSON with Javscript, Ajax, Perl etc from where you can take yourself to next levels.
Before proceeding with this tutorial you should have a basic understanding of how web application work over HTTP and we assume that you have basic knowledge of JavaScript.
JSON or JavaScript Object Notation is a lightweight is a text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers which include C, C++, Java, Python, Perl etc.
·         JSON stands for JavaScript Object Notation.
·         This format was specified by Douglas Crockford.
·         This was designed for human-readable data interchange
·         JSON has been extended from the JavaScript scripting language.
·         JSON filename extension is .json
·         JSON Internet Media type is application/json
·         The Uniform Type Identifier is public.json
Uses of JSON
·         JSON is used when writing JavaScript based application which includes browser extension and websites.
·         JSON format is used for serializing & transmitting structured data over network connection.
·         JSON is primarily used to transmit data between server and web application.
·         Web Services and API.s use JSON format to provide public data.
·         JSON can be used with modern programming languages.
Characteristics of JSON
·         It is easy to read and write JSON.
·         JSON is lightweight text based interchange format
·         JSON is language independent.
Simple Example in JSON
Example shows Books information stored using JSON considering language of books and there editions:
{
    "book": [
    {
       "id":"01",
       "language": "Java",
       "edition": "third",
       "author": "Herbert Schildt"
    },
    {
       "id":"07",
       "language": "C++",
       "edition": "second"
       "author": "E.Balagurusamy"
    }]
}
After understanding the above program we will try another example, let's save the below code as json.htm:
<html>
<head>
<title>JSON example</title>
<script language="javascript" >
 
  var object1 = { "language" : "Java", "author"  : "herbert schildt" };
  document.write("<h1>JSON with JavaScript example</h1>");
  document.write("<br>");
  document.write("<h3>Language = " + object1.language+"</h3>"); 
  document.write("<h3>Author = " + object1.author+"</h3>");  

  var object2 = { "language" : "C++", "author"  : "E-Balagurusamy" };
  document.write("<br>");
  document.write("<h3>Language = " + object2.language+"</h3>"); 
  document.write("<h3>Author = " + object2.author+"</h3>");  
  
  document.write("<hr />");
  document.write(object2.language + " programming language can be studied " +
  "from book written by " + object2.author);
  document.write("<hr />");
 
</script>
</head>
<body>
</body>
</html>
Now let's try to open json.htm using IE or any other javascript enabled browser, this produces the following result:
json example
JSON - Syntax
Let's have a quick look on JSON basic syntax. JSON syntax is basically considered as subset of JavaScript syntax, it includes the following:
·         Data is represented in name/value pairs
·         Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
·         Square brackets hold arrays and values are separated by ,(comma).
Below is a simple example:
{
    "book": [
    {
       "id":"01",
       "language": "Java",
       "edition": "third",
       "author": "Herbert Schildt"
    },
    {
       "id":"07",
       "language": "C++",
       "edition": "second"
       "author": "E.Balagurusamy"
    }]
}
JSON supports following two data structures:
·         Collection of name/value pairs: This Data Structure is supported by different programming language.
·         Ordered list of values: It includes array, list, vector or sequence etc.
JSON - DataTypes
There are following datatypes supported by JSON format:
Type
Description
Number
double- precision floating-point format in JavaScript
String
double-quoted Unicode with backslash escaping
Boolean
true or false
Array
an ordered sequence of values
Value
it can be a string, a number, true or false, null etc
Object
an unordered collection of key:value pairs
Whitespace
can be used between any pair of tokens
null
empty
Number
·         It is a double precision floating-point format in JavaScript and it depends on implementation.
·         Octal and hexadecimal formats are not used.
·         No NaN or Infinity is used in Number.
The following table shows number types:
Type
Description
Integer
Digits 1-9, 0 and positive or negative
Fraction
Fractions like .3, .9
Exponent
Exponent like e, e+, e-,E, E+, E-
Syntax:
var json-object-name = { string : number_value, .......}
Example:
Example showing Number Datatype, value should not be quoted:
var obj = {marks: 97}
String
·         It is a sequence of zero or more double quoted Unicode characters with backslash escaping.
·         Character is a single character string i.e. a string with length 1.
The table shows string types:
Type
Description
"
double quotation
\
reverse solidus
/
solidus
b
backspace
f
form feed
n
new line
r
carriage return
t
horizontal tab
u
four hexadecimal digits
Syntax:
var json-object-name = { string : "string value", .......}
Example:
Example showing String Datatype:
var obj = {name: 'Amit'}
Boolean
It includes true or false values.
Syntax:
var json-object-name = { string : true/false, .......}
Example:
var obj = {name: 'Amit', marks: 97, distinction: true}
Array
·         It is an ordered collection of values.
·         These are enclosed square brackets which means that array begins with .[. and ends with .]..
·         The values are separated by ,(comma).
·         Array indexing can be started at 0 or 1.
·         Arrays should be used when the key names are sequential integers.
Syntax:
[ value, .......]
Example:
Example showing array containing multiple objects:
{
  "books": [
   { "language":"Java" , "edition":"second" },
   { "language":"C++" , "lastName":"fifth" },
   { "language":"C" , "lastName":"third" }
  ]
}
Object
·         It is an unordered set of name/value pairs.
·         Object are enclosed in curly braces that is it starts with '{' and ends with '}'.
·         Each name is followed by ':'(colon) and the name/value pairs are separated by , (comma).
·         The keys must be strings and should be different from each other.
·         Objects should be used when the key names are arbitrary strings
Syntax:
{ string : value, .......}
Example:
Example showing Object:
{
"id": "011A",
"language": "JAVA",
"price": 500,
}
Whitespace
It can be inserted between any pair of tokens. It can be added to make code more readable. Example shows declaration with and without whitespace:
Syntax:
{string:"   ",....}
Example:
var i= "   sachin";
var j = "  saurav"
null
It means empty type.
Syntax:
null
Example:
var i = null;

if(i==1)
{
   document.write("<h1>value is 1</h1>");    
}
else
{
   document.write("<h1>value is null</h1>");
}
JSON Value
It includes:
·         number (integer or floating point)
·         string
·         boolean
·         array
·         object
·         null
Syntax:
String | Number | Object | Array | TRUE | FALSE | NULL
Example:
var i =1;
var j = "sachin";
var k = null;
JSON - Objects
Creating Simple Objects
JSON objects can be created with Javascript. Let's us see various ways of creating JSON objects using Javascript:
·         Creation of an empty Object:
var JSONObj = {};
·         Creation of new Object:
var JSONObj = new Object();
·         Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attributes is accessed by using '.' Operator:
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
This is an example which shows creation of an object in javascript using JSON, save the below code as json_object.htm:
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language="javascript" >

  var JSONObj = { "name" : "tutorialspoint.com", "year"  : 2005 };
  document.write("<h1>JSON with JavaScript example</h1>");
 document.write("<br>");
  document.write("<h3>Website Name="+JSONObj.name+"</h3>"); 
  document.write("<h3>Year="+JSONObj.year+"</h3>"); 

</script>
</head>
<body>
</body>
</html>
Now let's try to open json_object.htm using IE or any other javascript enabled browser, this produces the following result:
json objects
Creating Array Objects
Below example shows creation of an array object in javascript using JSON, save the below code as json_array_object.htm:
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >

document.writeln("<h2>JSON array object</h2>");

var books = { "Pascal" : [
      { "Name"  : "Pascal Made Simple", "price" : 700 },
      { "Name"  : "Guide to Pascal", "price" : 400 }
   ],                      
   "Scala"  : [
      { "Name"  : "Scala for the Impatient", "price" : 1000 },
      { "Name"  : "Scala in Depth", "price" : 1300 }
   ]   
}   

var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{      
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Pascal[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Pascal[i].price +"</td></tr>");
   document.writeln("</table>");
   document.writeln("</td>");
}

for(i=0;i<books.Scala.length;i++)
{
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Scala[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Scala[i].price+"</td></tr>");
   document.writeln("</table>");
   document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open json_array_object.htm using IE or any other javascript enabled browser, this produces the following result:
json array objects
JSON - Schema
JSON Schema is a specification for JSON based format for defining structure of JSON data. It was written under IETF draft which expired in 2011. JSON Schema:
·         Describes your existing data format.
·         Clear, human- and machine-readable documentation.
·         Complete structural validation, useful for automated testing.
·         Complete structural validation, validating client-submitted data.
JSON Schema Validation Libraries
There are several validators currently available for different programming languages. Currently the most complete and compliant JSON Schema validator available is JSV
Languages
Libraries
C
WJElement (LGPLv3)
Java
json-schema-validator (LGPLv3)
.NET
Json.NET (MIT)
ActionScript 3
Frigga (MIT)
Haskell
aeson-schema (MIT)
Python
Jsonschema
Ruby
autoparse (ASL 2.0); ruby-jsonschema (MIT)
PHP
php-json-schema (MIT). json-schema (Berkeley)
JavaScript
Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere (modified BSD or AFL 2.0); schema.js.
JSON Schema Example
Following is a basic JSON schema which covers a classical product catalog description:
{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        }
    },
    "required": ["id", "name", "price"]
}
Let's check various important keywords which can be used in this schema:
Keywords
Description
$schema
The $schema keyword states that this schema is written according to the draft v4 specification.
title
You will use this to give a title to your schema
description
A little description of the schema
type
The type keyword defines the first constraint on our JSON data: it has to be a JSON Object.
properties
Defines various keys and their value types, minimum and maximum values to be used in JSON file.
required
This keeps a list of required properties.
minimum
This is the constraint to be put on the value and represents minimum acceptable value.
exclusiveMinimum
If "exclusiveMinimum" is present and has boolean value true, the instance is valid if it is strictly greater than the value of "minimum".
maximum
This is the constraint to be put on the value and represents maximum acceptable value.
exclusiveMaximum
If "exclusiveMaximum" is present and has boolean value true, the instance is valid if it is strictly lower than the value of "maximum".
multipleOf
A numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's value is an integer.
maxLength
The length of a string instance is defined as the maximum number of its characters.
minLength
The length of a string instance is defined as the minimum number of its characters.
pattern
A string instance is considered valid if the regular expression matches the instance successfully.
You can check a http://json-schema.org for complete list of keywords which can be used in defining JSON schema. Above schema can be used to test the validity of the below given JSON code:
[
    {
        "id": 2,
        "name": "An ice sculpture",
        "price": 12.50,
    },
    {
        "id": 3,
        "name": "A blue mouse",
        "price": 25.50,
    }
]
JSON - Comparison with XML
JSON and XML are human readable formats and are language independent. They both have support for creation, reading and decoding in real world situations. We can compare JSON with XML based on the following factors:
Verbose
XML is more verbose than JSON, so it's faster to write JSON for humans.
Arrays Usage
XML is used to describe structured data which doesn't include arrays whereas JSON include arrays.
Parsing
JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object.
Example
This shows individual examples of XML and JSON:
JSON
{
   "company": Volkswagen,
   "name": "Vento",
   "price": 800000
}
XML
<car>
   <company>Volkswagen</company>
   <name>Vento</name>
   <price>800000</price>
</car>


JSON with Ajax
Ajax is Asynchronous JavaScript and XML which is used on client side as group of interrelated web development techniques in order to create asynchronous web applications. According to Ajax model, web applications can send data and retrieve data from a server asynchronously without interfering with the display, behavior of existing page.
Many developers use JSON to pass AJAX updates between client and server. Websites updating live sports scores can be considered as an example of AJAX. If these scores have to be updated on the website, then they must be stored on the server so that the webpage can retrieve the score when it is required. This is where we can make use of JSON formatted data.
Any data that is updated using AJAX can be stored using the JSON format on web server. Ajax is used so that javascript can retrieve these JSON files when necessary, they parse them and then does of the two:
·         Store the parsed values in variables for further processing before displaying them on the webpage
·         It directly assign the data to the DOM elements in the webpage, so that it gets displayed on the website.
Example
The below code shows JSON with Ajax, save it in ajax.htm file. Here loading function loadJSON() will be used asynchronously to upload JSON data.
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON()
{
   var data_file = "http://www.tutorialspoint.com/json/data.json";
   var http_request = new XMLHttpRequest();
   try{
      // Opera 8.0+, Firefox, Chrome, Safari
      http_request = new XMLHttpRequest();
   }catch (e){
      // Internet Explorer Browsers
      try{
         http_request = new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e) {
         try{
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         }catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
         }
      }
   }
   http_request.onreadystatechange  = function(){
      if (http_request.readyState == 4  )
      {
        // Javascript function JSON.parse to parse JSON data
        var jsonObj = JSON.parse(http_request.responseText);

        // jsonObj variable now contains the data structure and can
        // be accessed as jsonObj.name and jsonObj.country.
        document.getElementById("Name").innerHTML =  jsonObj.name;
        document.getElementById("Country").innerHTML = jsonObj.country;
      }
   }
   http_request.open("GET", data_file, true);
   http_request.send();
}
</script>
<title>narendra86.blogspot.in JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class="src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id="Name">Sachin</div></td>
<td><div id="Country">India</div></td></tr>
</table>

<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>
Following is the input file data.json having data in JSON format which will be uploaded asynchronously when we click Update Detail button. This file is being kept in http://www.tutorialspoint.com/json/
{"name": "brett", "country": "Australia"}
Above HTML code will generate following screen, where you can check AJAX in action:
Cricketer Details
Name
  Country
Sachin
   India
When you click on Update Detail button, you should get a result something as follows, you can try it yourself JSON with AJAX provided your browser supports Javascript.
Cricketer Details
Name
Country
brett
Australia




<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>

<p>
Name: <span id="jname"></span><br />
Age: <span id="jage"></span><br />
Address: <span id="jstreet"></span><br />
Phone: <span id="jphone"></span><br />
</p>

<script>
var JSONObject= {
"name":"John Johnson",
"street":"Oslo West 555",
"age":33,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>

</body>
</html>


JSON Object Creation in JavaScript

Name: John Johnson
Age: 33
Address: Oslo West 16
Phone: 555 1234567

Much 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

Much Unlike XML

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

Why JSON?

For AJAX applications, JSON is faster and easier than XML:
Using XML
  • Fetch an XML document
  • Use the XML DOM to loop through the document
  • Extract values and store in variables
Using JSON
  • Fetch a JSON string
  • eval() the JSON string

Json  with JavaScript
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>First Name: <span id="fname"></span></p>

<script>
var employees = [
{ "firstName" : "John" , "lastName" : "Doe" },
{ "firstName" : "Anna" , "lastName" : "Smith" },
{ "firstName" : "Peter" , "lastName" : "Jones" }, ];
employees[1].firstName="Jonatan";
document.getElementById("fname").innerHTML=employees[1].firstName;
</script>

</body>
</html>
 

Create Object from JSON String

First Name: Jonatan



function loadFlickr(flickrid)
{
 // Display a loading icon in our display element
 $('#feed').html('<span><img src="images/lightbox-ico-loading.gif" /></span>');

 // Request the JSON and process it
 $.ajax({
  type:'GET',
  url:"http://api.flickr.com/services/feeds/photos_public.gne",
  data:"id="+flickrid+"&lang=en-us&format=json&jsoncallback=?",
  success:function(feed) {
   // Create an empty array to store images
   var thumbs = [];

   // Loop through the items
   for(var i=0, l=feed.items.length; i < l && i < 16; ++i) 
   {
    // Manipulate the image to get thumb and medium sizes
    var img = feed.items[i].media.m.replace(
     /^(.*?)_m\.jpg$/, 
     '<a href="$1.jpg"><img src="$1_s.jpg" alt="" /></a>'
    );

    // Add the new element to the array
    thumbs.push(img);
   }

   // Display the thumbnails on the page
   $('#feed').html(thumbs.join(''));

   // A function to add a lightbox effect
   addLB();
  },
  dataType:'jsonp'
 });
}

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...