Thursday, December 10, 2009

JSONP

HI

Here i will show you how jsonp works.
Let's first dive into details and then later we gonna see an example on jsonp.

DETAILS:


"JSONP" stands for JavaScirpt Object Notations with Padding.
we already know JSON is one of the data formats used on web.
and we also know that AJAX doesn't allow us to fetch data from cross-Domain sites.
(here Ajax is Browser's Native Object and not RIA's Object).
ofcourse it's possible with RIA controls on Browser like Silverlight, Flash using policy files.


For work-around solution to this restriction, JSONP comes into the scene.
JSONP is not a new technology, it's a simple idea, (just like AJAX,) it uses existing technologies.
JSONP is used for data fetching (in JSON Format) from cross-Domain and same-Domain sites using
"javascript" tag's "src" attribute.


After data has been received, it calls a callback function, which is padded to the URL value of "src" attribute.
Confused? see the example below.


VULNERABILITIES:

JSONP vulnerable to cross site scripting attacks (XSS).
so don't use it for sensitive data fetching.
and use it with trusted sites only.




EXAMPLE:


In this example, i will show you how to fetch data from same-Domain site using asp.net.
>create a new asp.net project and name it 'TestSite" and open it.
>create a new folder called "jsonp".
>create a new html file under jsonp folder, and name it "jsonp.html"
>and write this code in it.


<htmL>
<head>
<script type="text/javascript">
function callme(obj)
{
txt.value="value one:"+obj.two[0];
txt.value+=" value two:"+obj.two[1];
txt.value+=" ";
txt.value+="Obj one val:"+obj.one;
}
</script>
</head>
<body>
testing jsonp! <i>callback function should be defined first, then get jsonp using javascript src.</i><br/>
<textarea id="txt" cols="20" rows="4">
</textarea>
<script type="text/javascript" src="http://localhost:1049/TestSite/JsonP/Handler.ashx?jsonp=callme">
</script>
</body>
</html>

Now create an asp.net handler file under jsonp folder, and name it, "jsonp.ashx"


using System;
using System.Web;

public class Handler : IHttpHandler
{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/javascript";
string callbackFuncName=context.Request.QueryString["jsonp"].ToString();
string json = "{'one':'rozyrojz','two':[1,2]}";
context.Response.Write(callbackFuncName+"("+json+");");
}
public bool IsReusable {
get { return false; }
}
}

Now run the jsonp.html. That's it!

REFERENCES:
***> http://neil.fraser.name/news/2009/07/27/
**> http://www.west-wind.com/Weblog/posts/107136.aspx
*> http://niryariv.wordpress.com/2009/05/05/jsonp-quickly/


Thanks for reading!