XML HTTP object

Sunday, October 31, 2010

XMLHttpRequest (XHR) is an API available in web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script The data might be received from the server as XML text or as plain text. Data from the response can be used directly to alter the DOM of the currently active document in the browser window without loading a new web page document. The response data can also be evaluated by the client-side scripting. For example, if it was formatted as JSON by the web server, it can easily be converted into a client-side data object for further use.
XMLHttpRequest has an important role in the Ajax web development technique. It is currently used by many websites to implement responsive and dynamic web applications. Examples of these web applications include Gmail, Google Maps, Facebook, and many others.


Internet Explorer on Windows, Safari on Mac OS-X, Mozilla on all platforms, Konqueror in KDE, IceBrowser on Java, and Opera on all platforms including Symbian provide a method for client side javascript to make HTTP requests. From the humble begins as an oddly named object with few admirers, it's blossomed to be the core technology in something called AJAX .
The Object makes many things easier and neater than they other would be, and introduces some things that were otherwise impossible such as HEAD requests to see when a resource was last modified, or to see if it even exists. It makes your scripting options more flexible allowing for POST requests without having the page change, and opens up the possibility of using PUT, DELETE etc. These methods are increasingly used to provide richer Web Applications like G-Mail that use lower bandwidth and offer snappier user interaction.

Why XML HTTP Request object?

Whilst the object is called the XML HTTP Request object it is not limited to being used with XML, it can request or send any type of document, although dealing with binary streams can be problematical in javascript

What is AJAX?

AJAX, an acronym for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability.

Creating the Object

Creating an instance of the XMLHttpRequest.object is important for Ajax. It differs for browsers.

For Safari and Mozilla:
var XmlHttp = new XMLHttpRequest();


For Internet Explorer:
var XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");


The object reference returned by both constructors is to an abstract object that works entirely out of view of the user. Its methods control all operations, while its properties hold, among other things, various data pieces returned from the server.

Object Methods

Instances of the XMLHttpRequest object in all supported environments share a concise, but powerful, list of methods and properties. The following table shows the supported methods and their jobs.


Common XMLHttpRequest Object Methods

Method
Description
abort()
Abort the current request
getAllResponseHeaders()
Get the complete set of headers (labels and values) as a string
getResponseHeader("headerLabel")
Get the string value of a single header label
send(content)
Transfers the request, optionally with postable string or DOM object data
setRequestHeader("label", "value")
Sets a label/value pair to the header to be sent with a request

Example for Creating the XMLHTTP Object
<script language="javascript">
  //Global XMLHTTP Request object
var XmlHttp;
//Creating and setting the instance of appropriate XMLHTTP Request object to 
//a "XmlHttp" variable  
function CreateXmlHttp()
{
 //Creating object of XMLHTTP in Internet Explorer
 try
 {
  XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 }
 catch(e)
 {
  try
  {
   XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(oc)
  {
   XmlHttp = null;
  }
 }
 //Creating object of XMLHTTP in Mozilla and Safari 
 if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
 {
  XmlHttp = new XMLHttpRequest();
 }
}
</script>


The open method is to specify the attributes like URL, send method, etc.

Method
Description
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName)
open( method, URL, async, userName, password)
Assigns destination URL, method, and other optional attributes of a pending request

Two main required parameters are the HTTP method you intend for the request and the URL for the connection. For the method parameter, use "GET" on operations that are primarily data retrieval requests; use "POST" on operations that send data to the server, especially if the length of the outgoing data is potentially greater than 512 bytes. The URL may be either a complete or relative URL.
An important optional third parameter is a Boolean value that controls whether the upcoming transaction should be handled asynchronously. The default behavior (true) is to act asynchronously, which means that script processing carries on immediately after the send() method is invoked, without waiting for a response.
If you set this value to false, however, the script waits for the request to be sent and for a response to arrive from the server. While it might seem like a good idea to wait for a response before continuing processing, you run the risk of having your script hang if a network or server problem prevents completion of the transaction. It is safer to send asynchronously and design your code around the onreadystatechange event for the request object.
The following generic function includes branched object creation, event handler assignment, and submission of a GET request. A single function argument is a string containing the desired URL. The function assumes that a global variable, req, receives the value returned from the object constructors. Using a global variable here allows the response values to be accessed freely inside other functions elsewhere on the page. Also assumed in this example is the existence of a processReqChange() function that will handle changes to the state of the request object.
var requestUrl = "WebForm2.aspx" + "?SelectedCountry=" + (selectedCountry);
 CreateXmlHttp();
 
 // If browser supports XMLHTTPRequest object
 if(XmlHttp)
 {
  //Setting the event handler for the response
  XmlHttp.onreadystatechange = HandleResponse;
  
  //Initializes the request object with GET (METHOD of posting), 
  //Request URL and sets the request as asynchronous.
  XmlHttp.open("GET", requestUrl,  true);
  
  //Sends the request to server
  XmlHttp.send(null);  
 }
It is essential that the data returned from the server be sent with a Content-Type set to text/xml. Content that is sent as text/plain or text/html is accepted by the instance of the request object, however it will only be available for use via the responseText property.

Object Properties

Property
Description
onreadystatechange
Event handler for an event that fires at every state change
readyState
Object status integer:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText
String version of data returned from server process
responseXML
DOM-compatible document object of data returned from server process
statusText
String message accompanying the status code

Another property is status.
This will intimate the status of the request.
Refer to the article "Dropdown Box Using AJAX" for a complete list of statuses.
I hope this article will help learners of Ajax to understand the xmlhttp object


How do I make a request?

Making a HTTP request is very simple. You tell the XML HTTP request object what sort of HTTP request you want to make and which url you want to request. Provide a function to be called when as the request is being made, and finally what, (if any) information you want sent along in the body of the request.
The following script makes a GET request for the relative url "text.txt" (relative to the calling page) It provides the function, which checks the readyState property each time it's called and when it has the value 4 - meaning the load is complete, it displays the responseText to the user with an alert.
xmlhttp.open("GET", "test.txt",true);
 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4) {
   alert(xmlhttp.responseText)
  }
 }
 xmlhttp.send(null)

HTTP request

The following sections demonstrate how a request using the XMLHttpRequest object functions within a conforming user agent based on the W3C Working Draft. As the W3C standard for the XMLHttpRequest object is still a draft, user agents may not abide by all the functionings of the W3C definition and any of the following is subject to change. Extreme care should be taken into consideration when scripting with the XMLHttpRequest object across multiple user agents. This article will try to list the inconsistencies between the major user agents.

The open method

The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through the open method. This method must be invoked prior to the actual sending of a request to validate and resolve the request method, URL, and URI user information to be used for the request. This method does not assure that the URL exists or the user information is correct. This method can accept up to five parameters, but requires only two, to initialize a request.
The first parameter of the method is a text string indicating the HTTP request method to use. The request methods that must be supported by a conforming user agent, defined by the
W3C draft for the XMLHttpRequest object, are currently listed as the following.

  • GET (Supported by IE7+, Mozilla 1+)
  • POST (Supported by IE7+, Mozilla 1+)
  • HEAD (Supported by IE7+)
  • PUT
  • DELETE
  • OPTIONS (Supported by IE7+)
However, request methods are not limited to the ones listed above. The W3C draft states that a browser may support additional request methods at their own discretion.
The second parameter of the method is another text string, this one indicating the URL of the HTTP request. The W3C recommends that browsers should raise an error and not allow the request of a URL with either a different port or ihost URI component from the current document.
The third parameter, a boolean value indicating whether or not the request will be asynchronous, is not a required parameter by the W3C draft. The default value of this parameter should be assumed to be true by a W3C conforming user agent if it is not provided. An asynchronous request ("true") will not wait on a server response before continuing on with the execution of the current script. It will instead invoke the onreadystatechange event listener of the XMLHttpRequest object throughout the various stages of the request. A synchronous request ("false") however will block execution of the current script until the request has been completed, thus not invoking the onreadystatechange event listener.
The fourth and fifth parameters are the username and password, respectively. These parameters, or just the username, may be provided for authentication and authorization if required by the server for this request.

 The setRequestHeader method

Upon successful initialization of a request, the setRequestHeader method of the XMLHttpRequest object can be invoked to send HTTP headers with the request. The first parameter of this method is the text string name of the header. The second parameter is the text string value. This method must be invoked for each header that needs to be sent with the request. Any headers attached here will be removed the next time the open method is invoked in a W3C conforming user agent.

 The send method

To send an HTTP request, the send method of the XMLHttpRequest must be invoked. This method accepts a single parameter containing the content to be sent with the request. This parameter may be omitted if no content needs to be sent. The W3C draft states that this parameter may be any type available to the scripting language as long as it can be turned into a text string, with the exception of the DOM document object. If a user agent cannot stringify the parameter, then the parameter should be ignored.
If the parameter is a DOM document object, a user agent should assure the document is turned into well-formed XML using the encoding indicated by the inputEncoding property of the document object. If the Content-Type request header was not added through setRequestHeader yet, it should automatically be added by a conforming user agent as "application/xml;charset=charset," where charset is the encoding used to encode the document.
If the user agent is configured to use a proxy server, then the XMLHttpRequest object will modify the request appropriately so as to connect to the proxy instead of the origin server, and send Proxy-Authorization headers as configured.

 The onreadystatechange event listener

If the open method of the XMLHttpRequest object was invoked with the third parameter set to true for an asynchronous request, the onreadystatechange event listener will be automatically invoked for each of the following actions that change the readyState property of the XMLHttpRequest object.
Theoretically, state changes should work like this:

  • After the open method has been invoked successfully, the readyState property of the XMLHttpRequest object should be assigned a value of 1.
  • After the send method has been invoked and the HTTP response headers have been received, the readyState property of the XMLHttpRequest object should be assigned a value of 2.
  • Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object should be assigned a value of 3.
  • Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object should be assigned a value of 4.
However, the major user agents are inconsistent with the handling of the onreadystatechange event listener.

For example, the following should produce four alerts: 1,2,3,4
 
xmlhttp.open("GET","somepage.xml",true);
xmlhttp.onreadystatechange = checkData;
xmlhttp.send(null);
function checkData()
{
 alert(xmlhttp.readyState);
}
In fact, some browser versions may omit state changes #1 and/or #2; if the order of the first two lines is reversed, some browsers may cause state change #1 to fire twice (or continue to omit event #2).

The HTTP response

After a successful and completed call to the send method of the XMLHttpRequest, if the server response was valid XML and the Content-Type header sent by the server is understood by the user agent as an Internet media type for XML, the responseXML property of the XMLHttpRequest object will contain a DOM document object. Another property, responseText will contain the response of the server in plain text by a conforming user agent, regardless of whether or not it was understood as XML.

Ajax introduction

Sunday, October 24, 2010

Ajax (pronounced /ˈeɪdʒæks/) (shorthand for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages[citation needed]. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.
Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with, the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

Examples of applications using AJAX:

Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works



AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:
  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)
  AJAX applications are browser- and platform-independent!

1. XMLHttpRequest

AJAX (Asynchronous Javascript and XML) is like DHTML in that it is a combination of several existing technologies rather than being a single technology. In this case the technologies involved are Javascript, a server side language to handle the request, and a markup language to return the requested data with. The only common part of this technology is Javascript since different server side languages and markups can be used. Even with Javascript though we don't have a single standard way to use this technology because Internet Explorer (which introduced this concept before the standards were developed) has its own way of handling things.
The very first thing that we need to be able to do in order to retrieve something from the server to update the current web page (without reloading the whole page) is to create the object that will perform the processing for us. Modern browsers have a predefined class called XMLHttpRequest that we can use to define our object directly. Internet Explorer has provided five different interfaces to provide us with the functionality that we need each of which is accessed via AxtiveX. As each new version has improved the functioning of the object we want to grab the most recent version that is installed in the browser.
There are only a few different ways that we can code the creation of our new AJAX object. The following version is slightly more efficient than the alternatives that I have seen.
function createXMLHttp() {
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
else if (window.ActiveXObject) {
var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp",
"MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.5.0"];
for (var i = avers.length -1; i >= 0; i--) {
try {
httpObj = new ActiveXObject(avers[i]);
return httpObj;
} catch(e) {}
}
}
throw new Error('XMLHttp (AJAX) not supported');
}

var ajaxObj = createXMLHttp();
This code starts by checking if the XMLHttpRequest class exists. If it does then we use that to create our object. If it doesn't then we check if ActiveX is supported (which means that the browser is running Internet Explorer on Windows with ActiveX enabled). If it is then we try to create our object using the latest XMLHttp version (version 5.0). If that fails then we work our way back through the array trying each earlier version in turn until we find one that is installed in the browser and which therefore allows us to create our object. If all of those attempts fail or if neither XMLHttpRequest or ActiveX are supported then we throw an error to indicate that AJAX is not supported in this browser.

Technologies

The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax, Jesse James Garrett explained that the following technologies are incorporated:
  • HTML or XHTML and CSS for presentation
  • the Document Object Model (DOM) for dynamic display of and interaction with data
  • XML for the interchange of data, and XSLT for its manipulation
  • the XMLHttpRequest object for asynchronous communication
  • JavaScript to bring these technologies together
Since then, however, there have been a number of developments in the technologies used in an Ajax application, and the definition of the term Ajax. In particular, it has been noted that:
  • JavaScript is not the only client-side scripting language that can be used for implementing an Ajax application. Other languages such as VBScript are also capable of the required functionality.However JavaScript is the most popular language for Ajax programming due to its inclusion in and compatibility with the majority of modern web browsers.
  • XML is not required for data interchange and therefore XSLT is not required for the manipulation of data. JavaScript Object Notation (JSON) is often used as an alternative format for data interchange,[ although other formats such as preformatted HTML or plain text can also be used.
Classic Ajax involves writing ad hoc JavaScript on the client. A simpler if cruder alternative is to use standard JavaScript libraries that can partially update a page, such as ASP.Net's UpdatePanel. Tools (or web application frameworks) such as Echo and ZK enable fine grained control of a page from the server, using only standard JavaScript libraries.
Introducing XMLHttpRequest and pseudomultithreading, it is possible to swap the role of client and server (web browser may start behaving as a server and web server may start behaving as a client) in Client-Server models.

Drawbacks

  • Pages dynamically created using successive Ajax requests do not automatically register themselves with the browser's history engine, so clicking the browser's "back" button may not return the user to an earlier state of the Ajax-enabled page, but may instead return them to the last full page visited before it. Workarounds include the use of invisible IFrames to trigger changes in the browser's history and changing the URL fragment identifier (the portion of a URL after the '#') when Ajax is run and monitoring it for changes.
  • Dynamic web page updates also make it difficult for a user to bookmark a particular state of the application. Solutions to this problem exist, many of which use the URL fragment identifier (the portion of a URL after the '#') to keep track of, and allow users to return to, the application in a given state.
  • Depending on the nature of the Ajax application, dynamic page updates may interfere disruptively with user interactions, especially if working on an unstable internet connection. For instance, editing a search field may trigger a query to the server for search completions, but the user may not know that a search completion popup is forthcoming, and if the internet connection is slow, the popup list may show up at an inconvenient time, when the user has already proceeded to do something else.
  • Because most web crawlers do not execute JavaScript code,[ publicly indexable web applications should provide an alternative means of accessing the content that would normally be retrieved with Ajax, thereby allowing search engines to index it.
  • Any user whose browser does not support JavaScript or XMLHttpRequest, or simply has this functionality disabled, will not be able to properly use pages which depend on Ajax. Similarly, devices such as mobile phones, PDAs, and screen readers may not have support for the required technologies. Screen readers that are able to use Ajax may still not be able to properly read the dynamically generated content. The only way to let the user carry out functionality is to fall back to non-JavaScript methods. This can be achieved by making sure links and forms can be resolved properly and do not rely solely on Ajax.
  • The same origin policy prevents some Ajax techniques from being used across domains, although the W3C has a draft of the XMLHttpRequest object that would enable this functionality. Techniques exist to sidestep this limitation by using a special Cross Domain Communications channel embedded as an iframe within a page.
  • Like other web technologies, Ajax has its own set of vulnerabilities[which?] that developers must address. Developers familiar with other web technologies may have to learn new testing and coding methods to write secure Ajax applications.[
  • Ajax-powered interfaces may dramatically increase the number of user-generated requests to web servers and their back-ends (databases, or other). This can lead to longer response times and/or additional hardware needs.
  • The asynchronous, callback-style of programming required can lead to complex code that is hard to maintain or debug. [
  • Ajax cannot easily be read by screen-reading technologies, such as JAWS, without hints built into the corresponding HTML based on WAI-ARIA standards. Screen-reading technologies are used by individuals with an impairment that hinders or prevents the visually reading of content on a screen
FOR FURTHER INFORMATION
http://www.ibm.com/developerworks/web/library/wa-ajaxintro1.html
http://www.javapassion.com/ajax/AJAXBasics.pdf

JSON

JSON (an acronym for JavaScript Object Notation (pronounced /dʒeɪsɔːn/)) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for virtually every programming language.
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.
The JSON format is often used for serializing and transmitting structured data over a network connection. It is primarily used to transmit data between a server and web application, serving as an alternative to XML

Data types, syntax and example
JSON's basic types are:
  • Number (integer or real)
  • String (double-quoted Unicode with backslash escaping)
  • Boolean (true or false)
  • Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
  • Object (a collection of key:value pairs, comma-separated and enclosed in curly braces; the key must be a string)
  • null
The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, a number field for age, contains an object representing the person's address, and contains a list (an array) of phone number objects.
{
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address": 
     {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber": 
     [
         {
           "type": "home",
           "number": "212 555-1234"
         },
         {
           "type": "fax",
           "number": "646 555-4567"
         }
     ]
 }
A strictly bijective equivalent for the above in XML could be:
<Object>
  <Property><Key>firstName</Key>     <String>John</String></Property>
  <Property><Key>lastName</Key>      <String>Smith</String></Property>
  <Property><Key>age</Key>           <Number>25</Number></Property>
  <Property><Key>address</Key>
    <Object>
      <Property><Key>streetAddress</Key> <String>21 2nd Street</String></Property>
      <Property><Key>city</Key>          <String>New York</String></Property>
      <Property><Key>state</Key>         <String>NY</String></Property>
      <Property><Key>postalCode</Key>    <String>10021</String></Property>
    </Object>
  </Property>
  <Property><Key>phoneNumber</Key>
    <Array>
      <Object>
        <Property><Key>type</Key>          <String>home</String></Property>
        <Property><Key>number</Key>        <String>212 555-1234</String></Property>
      </Object>
      <Object>
        <Property><Key>type</Key>          <String>fax</String></Property>
        <Property><Key>number</Key>        <String>646 555-4567</String></Property>
      </Object>
    </Array>
  </Property>
</Object>
However, the following simplified XML using types (entities) is more likely be used by an XML practitioner:
<Person firstName="John" lastName="Smith" age="25">
  <Address streetAddress="21 2nd Street" city="New York" state="NY" postalCode="10021" />
  <PhoneNumbers>
    <PhoneNumber type="home" number="212 555-1234"/>
    <PhoneNumber type="fax"  number="646 555-4567"/>
  </PhoneNumbers>
</Person>

Note that while both the JSON and XML forms can carry the same data, the (second) XML example also conveys semantic content/meaning.
Since JSON is a subset of JavaScript it is possible (but not recommended) to parse the JSON text into an object by invoking JavaScript's eval() function. For example, if the above JSON data is contained within a JavaScript string variable contact, one could use it to create the JavaScript object p like so:
        
var p = eval("(" + contact + ")");
The contact variable must be wrapped in parentheses to avoid an ambiguity in JavaScript's syntax.
The recommended way, however, is to use a JSON parser. Unless a client absolutely trusts the source of the text, or must parse and accept text which is not strictly JSON-compliant, one should avoid eval(). A correctly implemented JSON parser will accept only valid JSON, preventing potentially malicious code from running.
Modern browsers, such as Firefox 3.5 and Internet Explorer 8, include special features for parsing JSON. As native browser support is more efficient and secure than eval(), it is expected that native JSON support will be included in the next ECMAScript standard
 JSON schema
There are several ways to verify the structure and data types inside a JSON object, much like an XML schema.
JSON Schema[  is a specification for a JSON-based format for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how it can be modified, much like what XML Schema provides for XML. JSON Schema is intended to provide validation, documentation, and interaction control of JSON data. JSON Schema is based on the concepts from XML Schema, RelaxNG, and Kwalify, but is intended to be JSON-based, so that JSON data in the form of a schema can be used to validate JSON data, the same serialization/deserialization tools can be used for the schema and data, and it can be self descriptive.

 Using JSON in Ajax

The following JavaScript code shows how the client can use an XMLHttpRequest to request an object in JSON format from the server. (The server-side programming is omitted; it has to be set up to respond to requests at url with a JSON-formatted string.)
var my_JSON_object = {}; 
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
  if (http_request.readyState == 4 && http_request.status == 200){
       my_JSON_object = JSON.parse( http_request.responseText );
  }
};
http_request.send(null);
Note that the use of XMLHttpRequest in this example is not cross-browser compatible; syntactic variations are available for Internet Explorer, Opera, Safari, and Mozilla-based browsers. The usefulness of XMLHttpRequest is limited by the same origin policy: the URL replying to the request must reside within the same DNS domain as the server that hosts the page containing the request. Alternatively, the JSONP approach incorporates the use of an encoded callback function passed between the client and server to allow the client to load JSON-encoded data from third-party domains and to notify the caller function upon completion, although this imposes some security risks and additional requirements upon the server.
Browsers can also use <iframe> elements to asynchronously request JSON data in a cross-browser fashion, or use simple <form action="url_to_cgi_script" target="name_of_hidden_iframe"> submissions. These approaches were prevalent prior to the advent of widespread support for XMLHttpRequest.
Dynamic <script> tags can also be used to transport JSON data. With this technique it is possible to get around the same origin policy but it is insecure. JSONRequest has been proposed as a safer alternative.

 Security issues

Although JSON is intended as a data serialization format, its design as a subset of the JavaScript programming language poses several security concerns. These concerns center on the use of a JavaScript interpreter to dynamically execute JSON text as JavaScript, thus exposing a program to errant or malicious script contained therein—often a chief concern when dealing with data retrieved from the internet. While not the only way to process JSON, it is an easy and popular technique, stemming from JSON's compatibility with JavaScript's eval() function, and illustrated by the following code examples.

 JavaScript eval()

Because all JSON-formatted text is also syntactically legal JavaScript code, an easy way for a JavaScript program to parse JSON-formatted data is to use the built-in JavaScript eval() function, which was designed to evaluate JavaScript expressions. Rather than using a JSON-specific parser, the JavaScript interpreter itself is used to execute the JSON data to produce native JavaScript objects.
Unless precautions are taken to validate the data first, the eval technique is subject to security vulnerabilities if the data and the entire JavaScript environment is not within the control of a single trusted source. If the data is itself not trusted, for example, it may be subject to malicious JavaScript code injection attacks. Also, such breaches of trust may create vulnerabilities for data theft, authentication forgery, and other potential misuse of data and resources. Regular expressions can be used to validate the data prior to invoking eval. For example, the RFC that defines JSON (RFC 4627) suggests using the following code to validate JSON before eval'ing it (the variable 'text' is the input JSON):
  
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
       text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
   eval('(' + text + ')');
A new function, JSON.parse(), has been proposed as a safer alternative to eval, as it is specifically intended to process JSON data and not JavaScript. It was to be included in the Fourth Edition of the ECMAScript standard, though it is available now as a JavaScript library at http://www.JSON.org/json2.js and will be in the Fifth Edition of ECMAScript.[citation needed]

Native JSON

Recent web browsers now either have or are working on native JSON encoding/decoding. This removes the eval() security problem above and also makes it faster because it doesn't parse functions. Native JSON is generally faster compared to the JavaScript libraries commonly used before. As of June 2009 the following browsers have or will have native JSON support:
At least 5 popular JavaScript libraries have committed to use native JSON if available:
Comparison with other formats

 XML

XML is often used to describe structured data and to serialize objects. Various XML-based protocols exist to represent the same kind of data structures as JSON for the same kind of data interchange purposes.
When data is encoded in XML, the result is typically larger in size than an equivalent encoding in JSON, mainly because of XML's closing tags. For example, ignoring irrelevant white space, the JSON encoding above for the "John Smith" data consumes 240 characters whereas the XML encoding consumes 313 characters. In this particular example, the XML encoding requires just over 30% more characters.
However, there are alternative ways to encode the same information. For example, XML allows the encoding of information in attributes, which are enclosed in quotes and thus have no end tags. Using attributes, an alternative XML encoding of the "John Smith" information is as follows:
<Person
  firstName='John'
  lastName='Smith'
  age='25'>
  <Address
    streetAddress='21 2nd Street'
    city='New York'
    state='NY'
    postalCode='10021'
  />
  <PhoneNumbers
    home='212 555-1234'
    fax='646 555-4567'
  />
</Person>
Not counting the irrelevant white-space, and ignoring the required XML header, this XML encoding only requires 200 characters, which may be compared with 215 characters for the equivalent JSON encoding:
{ 
  "Person": 
  {
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "Address": 
     {
        "streetAddress":"21 2nd Street",
        "city":"New York",
        "state":"NY",
        "postalCode":"10021"
     },
     "PhoneNumbers": 
     {
        "home":"212 555-1234",
        "fax":"646 555-4567"
     }
  }
}
The XML encoding may therefore be shorter than the equivalent JSON encoding, notably if the XML document uses attributes rather than elements. The main reason explaining here why the JSON is still longer is that all identifiers (object member names, represented as attribute names or element names in XML) are converted into strings between double quotes. As JSON does not support identifier types, and offers no shortcut for empty strings, all strings that don't contain any separator reserved for the JSON syntax and don't contain compressible whitespaces could be written without any double quotes, which represent here 38 characters (including 16 for string values that don't need any delimitation here): without these quotes, the JSON encoding would need only 181 characters.
But in general, the XML syntax is much longer than JSON because XML attributes are more restricted than text elements in the set of characters they accept, and cannot be used to represent repeated values of the same type with unlimited occurrences, or multiple occurrences of objects of the same type, and cannot represent ordered sequences with separate attributes: instead, XML will require using separate elements, and their recursive embedding will require to duplicate the element name in the closing tag of non-empty elements.
Each element type has also to be represented in a default property of each JSON object (because JSON objects are generic, like in JavaScript): here this is realized by assigning element names to the JSON object property with index "0", and numbering explicitly all elements in the content of an element.
JSON also does not offer a way for unifying objects and ordered (number-indexed) arrays, by automatically numbering object properties (like in PHP associative array initializers) to assign them default indexes (despite the fact that Javascript handles them the same way in expressions), when the XML syntax offers a builtin ordering of elements in the content of an element. Instead it just allows declaring separate arrays, that must be assigned to an explicitly named property of an object.
Beyond size, XML lacks an explicit mechanism for representing large binary data types such as image data (although binary data can be serialized in either case by applying a general-purpose binary-to-text encoding scheme such as one of the Base-64 variants). JSON can represent them using arrays of numbers (representing bytes, or larger integer units up to the precision of 52 bits including the sign bit), because it can exactly represent IEEE-754 64-bit doubles (as specified in the ECMAScript standard).
JSON also still lacks explicit references (something that XML has via extensions like XLink and XPointer, or that XML has natively via parsed external entities declared in the DTD for including external XML objects, or via unparsed external entities declared in the DTD with annotations for referencing any type of external object, or via attributes with IDREF types for internal references to elements in the same document); it also has no standard path notation comparable to XPath.

 PHP array initializers

PHP array initializers[citation needed], that are very similar to JSON objects, can represent exactly the same XML as above without having to specify an explicit numbering for ordering elements in the content of any parent element, using the same array object for representing all properties of an element object (the element name at index 0, all its attributes indexed by their name, and all child element objects in its content starting at index 1) and using string objects to represent all text elements, simply as:
array(
  "Person" => array(
    "firstName" => "John",
    "lastName" => "Smith",
    "age" => 25,
    "Address" => array(
      "streetAddress" => "21 2nd Street",
      "city" => "New York",
      "state" => "NY",
      "postalCode" => "10021"
    ),
    "PhoneNumbers" => array(
      "home" => "212 555-1234",
      "fax" => "646 555-4567"
    )
  )
)
One difference with JSON is that PHP arrays can make distinctions between integer values and floating-points, where JSON, JavaScript and ECMAScript only define a single Number type.
They can also contain references to other objects/arrays and store null references: this requires the use of PHP variables to store references of internal arrays instantiated within the initializer, and dereferencing this variable later in the content of the initializer, in order to create structures (However, it is not possible to create a circular structure or self-referencing array within a single PHP expression like an array initializer, because all members in the array will be instantiated before the array itself is instantiated and assignable into a variable). PHP array initializers can then create any directed acyclic graph from a single root but with possible common branches, when JSON data can only create acyclic tree structures without any common branches.
The boolean constants are represented with integers, but any type can be implicitly converted to a numeric type (strings are parsed and if they can't be converted or are empty, then their numeric value is zero). Then all numeric types or types implicitly convertible to numeric types are convertible to an integer by truncation. All integers are implicitly convertible to booleans (zero is considered false, non-zero is considered true), and other reference value types are considered true if they are non null.

The Basic Idea: Retrieving JSON via Script Tags

It's possible to specify any URL, including a URL that returns JSON, as the src attribute for a <script> tag.
Specifying a URL that returns plain JSON as the src-attribute for a script tag, would embed a data statement into a browser page. It's just data, and when evaluated within the browser's javascript execution context, it has no externally detectable effect.
One way to make that script have an effect is to use it as the argument to a function. invoke( {"Name": "Cheeso", "Rank": 7}) actually does something, if invoke() is a function in Javascript.
And that is how JSONP works. With JSONP, the browser provides a JavaScript "prefix" to the server in the src URL for the script tag; by convention, the browser provides the prefix as a named query string argument in its request to the server, e.g.,
<script type="text/javascript" 
         src="http://server2.example.com/getjson?jsonp=parseResponse">
 </script>
The server then wraps its JSON response with this prefix, or "padding", before sending it to the browser. When the browser receives the wrapped response from the server it is now a script, rather than simply a data declaration. In this example, what is received is
parseResponse({"Name": "Cheeso", "Rank": 7})
...which can cause a change of state within the browser's execution context, because it invokes a method.

 The Padding

While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser, it may also be a variable assignment, an if statement, or any other Javascript statement prefix.

Script Tag Injection

But to make a JSONP call, you need a script tag. Therefore, for each new JSONP request, the browser must add a new <script> tag—in other words, inject the tag—into the HTML DOM, with the desired value for the src attribute. This element is then evaluated, the src URL is retrieved, and the response JSON is evaluated.
In that way, the use of JSONP can be said to allow browser pages to work around the same origin policy via script tag injection.

 Basic Security concerns

Because JSONP makes use of script tags, calls are essentially open to the world. For that reason, JSONP may be inappropriate for carrying sensitive data. Including script tags from remote sites allows the remote sites to inject any content into a website. If the remote sites have vulnerabilities that allow JavaScript injection, the original site can also be affected.

 Cross-site request forgery

Naïve deployments of JSONP are subject to cross-site request forgery attacks (CSRF or XSRF).[23] Because the HTML <script> tag does not respect the same origin policy in web browser implementations, a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page, possibly divulging passwords or other sensitive data if the user is currently logged into the other site.
This is only a problem if the JSON-encoded data contains sensitive information that should not be disclosed to a third party, and the server depends on the browser's Same Origin Policy to block the delivery of the data in the case of an improper request. There is no problem if the server determines the propriety of the request itself, only putting the data on the wire if the request is proper. Cookies are not by themselves adequate for determining if a request was authorized. Exclusive use of cookies is subject to cross-site request forgery

FOR FURTHER INFORMATION
http://www.json.org/
http://www.javapassion.com/ajax/JSON.pdf
http://jsonformatter.curiousconcept.com/
http://www.roseindia.net/tutorials/json/
http://www.secretgeek.net/json_3mins.asp