Wednesday, December 22, 2010

Configuring simple JSONP server and client

I am working in a project which is modular. The modules run in different servers. I was planning to get the list of departments from one module to the other using JSON (because it’s cool). However, for me, the limitation in working with JSON was “Same Origin Policy”. I couldn’t request for the JSON data from one of my modules to the other module running in different server (different protocol, port or the IP).
The solution to the problem was using JSONP instead. We create a function in the server which will process requests from the client and sends back not only the JSON data, but also the callback function that the client must call. This way, when we request to the server using
tag, the function created in our client side is called with the callback and we can use the JSON data according to the format.
<script type="text/javascript">

Quick Server in PHP

<?php
header('Content-type: application/json;charset=UTF-8');
$jsonData;
$type = $_GET['parentDept'];
if($type == 'OPD'){
$jsonData = '[
{"deptId": "3", "label":"OPD:Eye"},
{"deptId": "4", "label":"OPD:Ortho"}
]';
}
else{
$jsonData = '[
{"deptId": "1", "label":"Laboratory"},
{"deptId": "2", "label":"Imaging"}
]';
}
echo $_GET['callback'] . '(' . $jsonData . ');';
?>


server finds the callback parameter value and appends it to be returned as the function with the JSON data into it. Also note, we can add up other parameters (eg. parentDept) if needed.

Quick Client


<html>
<head>
<title>JSONP test</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="json.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("http://192.168.1.10/jsonp.php?parentDept=OPD&callback=?", function(data){
//alert(JSON.stringify(data));
var htmlString = '';
$.each(data, function(index, value){
htmlString += '<option value="' +value.deptId+'">'+ value.label +'</option>';
});
$("#selectField").html(htmlString)
});
});
</script>
Select Department:
<select id="selectField">
<option>None</option>
</select>
</body>
</html>

Here JQuery’s $.getJSON() is used which makes it easier for us to make JSONP call and process the callback function.
You can download the zip content of this simple project here.

Reference: Cross-domain communications with JSONP (ibm.com)

No comments:

Post a Comment