Cross-domain communications with JSONP using JavaScript and jQuery!

Asynchronous JavaScript and XML (Ajax) is the key technology driving the new generation of Web sites, popularly termed as Web 2.0 sites.Ajax allows for data retrieval in the background without interfering with the display and behavior of the Web application. Data is retrieved using the XMLHttpRequest function, which is an API that lets client-side JavaScript make HTTP connections to remote servers.

This approach, however, does not allow cross-domain communication because of restrictions imposed by the browser. If you try to request data from a different domain, you will get a security error.

The same-origin policy limitations:

The same-origin policy prevents a script loaded from one domain from getting or manipulating properties of a document from another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page.

How to resolve?

Technique 1:

One relatively simple way to overcome this limitation is to have the Web page request data from the Web server it originates from, and to have the Web server behave as a proxy relaying the request to the actual third-party servers. Although widely used, this technique isn’t scalable.

Technique 2:

Another way is to use frame elements to create new areas in the current Web page, and to fetch any third-party content using GET requests. After being fetched, however, the content in the frames would be subject to the same-origin policy limitations.

Technique 3 (Using JSONP):

A more promising way to overcome this limitation is to insert a dynamic script element in the Web page, one whose source is pointing to the service URL in the other domain and gets the data in the script itself. When the script loads, it executes.
It works because the same-origin policy doesn’t prevent dynamic script insertions and treats the scripts as if they were loaded from the domain that provided the Web page. But if this script tries to load a document from yet another domain, it will fail. Fortunately, you can improve this technique by adding JavaScript Object Notation (JSON) to the mix.

JSONP Using Javasript:

Your client-side code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
<title>jsonp</title>
</head>
<body>
<span></span>
<script>
//this function is the callback, it needs to be a global variable
function readResponse(response){
document.getElementsByTagName('SPAN')[0].innerHTML = response.time + ' is from  php file';
console.log(response);
}
(function(){
//note the "readResponse" at the end
var src = 'http://www.your-cross-domain.com/index.php?id=18&callback=readResponse',
script = document.createElement('SCRIPT');
script.src = src;
document.body.appendChild(script);
})();

</script>
</body>
</html>

Your server-side coding:

<?php
$array = array("time"=>time());
if($_GET['callback']){
header('Content-type: application/json');
echo $_GET['callback']."(".json_encode($array).")";
exit();
}
?>

JSONP using jQuery:

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<div id=”images”>
</div>
<script>
$.getJSON(“http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?”, {
tags: “cat”,
tagmode: “any”,
format: “json”
}, function (data) {
$.each(data.items, function (i, item) {
$(“<img/>”).attr(“src”, item.media.m).appendTo(“#images”);
if (i == 3) return false;
});
});
</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>