Monday, January 28, 2013

Resolving Same Origin Policy restrictions ( Cross Domain Issues) using JQuery Ajax Calls and JSONP

 

Being a  web developer , you must be at least one time used JQuery Ajax requests from your client end . And the growing popularity of HTML 5 demands more such calls . And the main headache occurs when you want to access some thing from server , which may be hosted in a different domain .

The commonly suggested solution to this problem is to use  “JSONP” as data type in your Ajax request . Even though the same thing is repeated in all forums , but none clearly mentions what is JSONP and how you can implement it for cross domain – “GET” requests .

JSONP

JSONP is an addition JSON request ( JSON with Padding )  , it wraps JSON in a function call.  For example, the following might be returned from the third-party server:

mycallback({"key" : "value"});

Code Snippet

In your regular JQuery Ajax Call , modify the “dataType “ Parameter to “jsonp”  and add a new parameter called “jsonpCallback” .  set the value to the call back function same as the one which you are going to specify in your server file. here in this example it is “mycallback”  . 

Your Script Would looking like the below

<script type="text/javascript">
var URL = "
http://MyServer/OL/version.txt";
$.ajax(URL, {
crossDomain: true,
dataType: "jsonp",
jsonpCallback: mycallback,
success: function (data, text, xhqr) {
alert(data.text);
},
error: function (xhqr) {
console.log("Error");
}
});
</script>

Now your client is ready to send and receive cross domain Ajax calls  .  Now we’ll have a look at your server side file from which you are returning some data to client side .

Now modify your server side file say for example “version.txt”   as shown below .

mycallback({"text" : "Hello World This Text is from cross domain server "})

The above statement is a method which wraps your Json Data .

Happy Coding Smile

 

No comments:

Post a Comment