jQuery’s getJSON function to retrieve data in JSON format; Same domain or cross-domain request

Today I want to share the problems I faced and its solution about using JSON with jQuery. JSON is a lightweight text-based open standard designed for human-readable data interchange. It is being popular nowadays and it has been used by some popular sites like Twitter. jQuery is one of the most popular javascript framework. jQuery has got Ajax function. It perform an asynchronous HTTP (Ajax) request. For working with JSON, we can use either $.ajax function with ‘dataType’ parameter as ‘json’ or simply use $.getJSON function. In the example I have used $.getJSON for simplicity.
First lets create a client page. In html part. We keep a div with certain id where our ajax returned data will be replaced. Now in scripting part we use getJSON function. Assumed you have already included jQuery library file.
javascript code

<script type="text/javascript">
jQuery(document).ready(function($){
 $.getJSON('http://nilambar.com.np/test/converterapi/converterapi.php?callback=?',
  function(result){
   var op='';
   op+= '<p>';
   op+=' '+result.mday;
   op+=' '+result.month;
   op+=' '+result.year;
          op+='   '+result.hours;
   op+=':'+result.minutes;
   op+='<p>';
   $('#opid').html(op);
  });
});
</script>

getJSON takes three parameters. One is url from where we are going to fetch. Second is the data to be sent and third parameter is callback function which would be executed if request is successful. You may be thinking why there is ‘callback=?’ in the url. This is used to treat the request as JSONP instead. JSON only allows the request under same domain whereas JSONP also supports cross-domain request.
Now lets setup our server page.Here is the example php page.

<?php
date_default_timezone_set('Asia/Katmandu');
$json_encoded=json_encode(getdate());
$callback=$_GET['callback'];
$op=$callback.'('.$json_encoded.')';
header('Content-type: text/html');
echo $op;
?>

In server we need to echo our data in JSON format. PHP has ‘json_encode’ function which can convert array into json encoded form. In the example, I have fetched current date & time and it is json encoded. There is little hack in the code. jQuery excepts the returned data as callbackFunction(json_data). This callbackFunction is automatically replaced in ? by jQuery while requesting. Here header content type is ‘text/html‘ . I tried with ‘application/json’ but it gives error ‘invalid label’ in firebug. So I tried ‘text/html’ and it
works perfect.
You can get twits from Twitter in JSON format. Use following url in $.getJSON function in jQuery. You need to replace USERNAME with your desired twitter screenname.

http://twitter.com/status/user_timeline/USERNAME.json?count=10&callback=?

Leave a Reply

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