pavanarya

Let us share the knowledge

Making Cross Domain ajax calls(JsonP)

with one comment

Hi,

Today i want to write something about making cross domain ajax calls from our asp.net code.

So generally we will make use of XMLHttpRequest to make ajax call. So for making cross domain ajax call i am using JASONP(also known as Jason padding)

Why Jsonp but not XMLHttpRequest

Now let me explain you the conditions that made me to make use of JsonP instead of using XmlHttpRequest.

"http://search.twitter.com/search.json?q=Sachin%20Tendulkar"

the above url is an api provided by twitter to search for tweets. If you execute this url in firefox or ie we will be getting a json text as an output on browser screen.
So i am planning to make use of that api in my code to retrive some tweets. The first thing that came into my mind is XmlHttpReuest to make the ajax call and retrive the data from that api. So wrote the following code.

<!DOCTYPE html>
<html>
	<head>
		<title>Tweet Streamer</title>

	</head>
	<body>
		<ul id="tweets"></ul>
		<script type="text/javascript">
		    function xmlhttpPost() {
		        var xmlHttpReq = false;
		        var self = this;
		        var strURL = "http://search.twitter.com/search.json?q=Sachin%20Tendulkar";
		        // Mozilla/Safari
		        if (window.XMLHttpRequest) {
		            self.xmlHttpReq = new XMLHttpRequest();
		        }
		        // IE
		        else if (window.ActiveXObject) {
		            self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		        }
		        self.xmlHttpReq.open('POST', strURL, true);
		        self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		        self.xmlHttpReq.onreadystatechange = function () {
		            if (self.xmlHttpReq.readyState == 4) {
		               alert(self.xmlHttpReq.responseText);
		            }
		        }
		        self.xmlHttpReq.send();
		    }


		</script>
        <input type=button onclick=xmlhttpPost(); value="xmlhttpPost" />

	</body>
</html>

When i executed the above html page in ie and after clicking on the button i am expecting an alert box but i got a javascript error. The description of the error is “Access Denied”.

The reason behind this error is there are few limitations with the browsers security model like we cannot make cross domain XmlHttpRequest and also if we use frames they should be from same domain. So as i am trying to make use of a cross domain url with XmlHttpHandler it is failing.

So inorder to overcome this problem Jsop(Json Padding) was proposed.

Json Padding(Jsonp)

It is very simple to make Jsonp calls but we should make some changes to our server side code that returns the json data. They are

1.Wrap the actual json data inside a function name(here function name is the callback function name. A call back function is a function that is executed after successful execution of a resource) as follow.

Server side changes:

string jsontext= "somefunction(\"{company: \'teschsolutions\', established:\'1989'}\")";
        Response.Write(jsontext);
        Response.End();
//somefunction("{company: 'teschsolutions', established:'1989'}")

Here the actual data is {company:’teschsolutions’,established:’1989′}.
And somefunction is the name of the call back function that we are supposed to execute at client side after the successful execution of the server side code.

Client Side:

1. Include the url that we are trying to execute as source in a tag. Like

This will execute the code at the speciifed url and returns the data.

2. Create a call back function (the name should be same as the one that we gave in the server side code). This call back function should handle the json data returned by the server(the src url specified above).

For example let us take an aspx page and a simple html page. Let us assume that the aspx page is the cross domain page we want to access from the html page. So let us see the JsonP implementation of it.

testjsonp.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class testjsonp : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string jsontext= "somefunction(\"{company: \'teschsolutions\', established:\'1989'}\")";
        Response.Write(jsontext);
        Response.End();
    }
}

This testjsonp.aspx returns the json data to the client that request this page.

dummyhtml.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <script>
            function somefunction(somedatfromaspxpage) {
                alert(somedatfromaspxpage);
            }
    </script>
    <script src="http://localhost:3051/Jsop/testjsonp.aspx"></script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

so in the dummyhtml.html page we are trying to execute the testjsop.aspx by including it as a src to the script tag. The result of testjsonp.aspx is somefunction(“{company: ‘teschsolutions’, established:’1989′}”) Now the call goes to the function somefunction() that we are having in our dummyhtml.html page. This function handles the json data returned by the remote url. If we use firebug we can get a brief idea on how it is handled. So from the above image we can see the source code of dummyhtml.html page after the url(testjsop.aspx) is executed. The data we are returning from testjsonp.aspx will be treated as a javascript code calling a function(callback function) and the actual json data is treated as a parameter to the call back function

<script type="text/javascript" src="testjsonp.aspx">// <![CDATA[
somefunction("{company: 'teschsolutions', established:'1989'}")
// ]]></script>

Using Jsonp with twitter api

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="makeuseof.aspx.cs" Inherits="makeuseof" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <script>
            function pav(somedatfromaspxpage) {
                alert(somedatfromaspxpage);
            }
    </script>
  <script src='http://search.twitter.com/search.json?q=Sachin%20Tendulkar&callback="pav"'></script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

So in the above example the name of callback function that is to be executed is sent as a query string parameter.

Drawbacks of JsonP

1.Security. suppose if the server side code returns some malicious code then we are going to execute to it from client side without any validation. This can open doors for many vulnerable attacks.
2.We don’t have error handling techniques for this. Suppose if we are making call to a page that doesn’t exist then we don’t have any technique to identify this 404 error from server.





About these ads

Written by pavanarya

December 10, 2011 at 2:05 pm

Posted in Asp.net, Java script

One Response

Subscribe to comments with RSS.

  1. Thanks, it help me a lot

    deep

    February 8, 2012 at 1:59 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: