Showing posts with label Programming Stuff. Show all posts
Showing posts with label Programming Stuff. Show all posts

Jun 14, 2010

Browser's have same origin policy for ajax requests which means you cannot make a cross domain ajax request.

To overcome this barrier the following methods may be used.

  1. Use JSONP
  2. Make a service proxy
  3. Use dynamic script element

In this post i will be explaining  about how to use JSONP . I will be writing a simple script in dojo that will communicate with twitter api and return user's latest tweet's. The dojo.io.script method works by sending name of the callback method along with the asynchronous request and on completion of the request the callback method is called automatically by server side code.
The code snippet for the request is shown below.

var init=function(){
    dojo.io.script.get({
    url:'http://api.twitter.com/1/statuses/user_timeline/ramannanda9.json?callback=statusCallback',
    timeout:15000,
    callbackParamName:statusCallback,
    error:errorHandler,
    });

}
I have not used the load parameter in the above get call because i have done processing in the callback method itself.

The data received is passed as a json object to the callback method statusCallback as shown below.
var statusCallback=function(response)
{
...}

The response object can now be parsed to get the relevant information.

The twitter box that you can see on the right side has been made using similar script.

The entire code can be seen below.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js" djconfig="parseOnLoad:true"></script>
<script type="text/javascript">
dojo.require("dojo.fx");
dojo.require("dojox.fx.text");
dojo.require("dojo.fx.easing");
dojo.require("dojox.widget.Toaster");
dojo.require("dojo.parser");
dojo.require("dojo.io.script");
var doAddInfo=true;
var intervalId;
 
 
var statusCallback=function(response)
{
    if(doAddInfo){
addInfo(response[0].user.name,response[0].user.screen_name,
response[0].user.description,
response[0].user.profile_image_url);
       }
       doAddInfo=false;
       addBird();
     var anims=[];
       for(var i=0;(i<response.length)&&(i<20);i++){
        var nodeName='index';  
        display_tweet(response[i],i);
  nodeName=nodeName+i;
  anims.push(dojox.fx.text.backspace({node:nodeName , interval:60 , fixed:true ,unhide:true}));
 }
 dojo.fx.chain(anims).play();
 
}
  var addInfo= function(username,screen_name,description,image){
 
     dojo.create("div",{id:'bigtext',align:'left',innerHTML:"<a href='http://www.twitter.com/"+screen_name+"'>"+"<img class='myimg'  src='"+image+"' width=50 height=50 /> </img></a>"+"<p align:'left'>"+username+"</p>"+"<p align='left' id='bio'>Bio:"+description+"</p>"},dojo.query("#twitter")[0],'first');
 
 
 }
var addBird=function(){
 
  if(dojo.byId('plainimg')==null){
dojo.create("div",{id:'plainimg',innerHTML:"<img src='http://dl.dropbox.com/u/42099017/smallflyingbirdsparklesright.png' width='50' height='50' />"},dojo.query("#bigtext")[0]);
}
else
    {
dojo.attr('plainimg',{innerHTML:"<img src='http://dl.dropbox.com/u/42099017/smallflyingbirdsparklesright.png' width='50' height='50' />"});
}
var mainbox=dojo.marginBox(dojo.byId("twitter"));
var imgbox=dojo.marginBox(dojo.byId("plainimg"));
 
dojo.fx.slideTo({node:dojo.byId('plainimg'),
left:mainbox.w-imgbox.w-50,duration:1500,
onEnd:function(){dojo.byId('plainimg').innerHTML="<img src='http://dl.dropbox.com/u/42099017/smallflyingbirdsparkles.png' align:'left' width='50' height='50' />";dojo.fx.slideTo({node:dojo.byId('plainimg'),
left:0,duration:1200,easing:dojo.fx.easing.elasticIn()}).play(); },easing:dojo.fx.easing.elasticOut()}).play();}
 
dojo.io.script.get({
    url:'http://api.twitter.com/1/statuses/user_timeline/ramannanda9.json?callback=statusCallback',
    timeout:30000,
    error:errorHandler
    });
 
var display_tweet=function(element,index){
var a='index'+index;
if(dojo.byId(a)==null){
dojo.create('div',{id:a,align:'left',innerHTML:"<p align='left'>"+element.text+"</p>"+"<a class='special' href='http://twitter.com/?status=@"+element.user.screen_name+"&in_reply_to_status_id="+element.id+"&in_reply_to="+element.user.screen_name+"'> reply"+"</a>"+"<hr/>"},dojo.query('#tweetbox')[0]);
}
else{
    dojo.attr(a,{innerHTML:"<p align='left'>"+element.text+"</p>"+"<a class='special' href='http://twitter.com/?status=@"+element.user.screen_name+"&in_reply_to_status_id="+element.id+"&in_reply_to="+element.user.screen_name+"'> reply"+"</a>"+"<hr/>"} );
 
}
}
var errorHandler= function(err){
    dojo.publish("error", [{message:"Twitter is too 'Busy' cant render tweets",type:"error",duration:0}]);
    window.clearInterval(intervalId);
}
dojo.addOnLoad(function (){
intervalId=window.setInterval(init,1000*60*5);
init();
 
});
   </script>
 <div id="twitter"><div id="tweetbox"></div></div>
<div dojotype="dojox.widget.Toaster" duration="0" messagetopic="error" positiondirection="tr-left" >
  </div>

Posted on Monday, June 14, 2010 by Unknown

Jun 16, 2009

What is the File Extension JSON ?

JSON is a lightweight, language independent "data " interchange format. It was derived from ECMAScript programming language standard. The MIME content type for it is application/json.
The file extension for it is .json. JSON defines a small set of formatting or rules for portable or language independent representation of data. JSON can represent four primitive types namely string, number, boolean, null and it can also be used to represent two structured types namely objects and arrays.

An object is a name-value pair similar to the dictionary data type in python where the name is a string and value can be string, number, null or boolean, object or array.
For example
:- A car can be represented in an object representation as;-
"cars":{"model":"2006", "manufacturer":"Audi","price":"20000 USD"} .
An array on the other hand is an ordered collection of similar data items.

JSON was designed to be minimal, portable and as a subset of Javascript. The JSON text is encoded in Unicode and default encoding is UTF-8. The code for generating JSON text from the XML representaion is available for programming languages like java, python, php.

The File Extension JSON is readily recognized and the JSON data is easily consumed by a simple javascript based script because it does not have to do any additional parsing. The following code snippet shows how you can use it to represent data with utmost ease.


{
"customers" : {
"customer" : {
"@attributes" : {
"id" : "2314"
},
"name" : "Raman deep",
"phone" : "9967345612",
"purchases": "30000 USD"
"address" : {
"street" : "23/25 Rajouri garden",
"city" : "New Delhi",
"state" : "Delhi",
"zip_code" : "654321"
}
}
}
}


whereas its xml representation is shown below and as can be seen by comparing these two representations that the former one is easy to parse as it uses javascript object and array data types to represent data and hence is used more nowadays.


<customer>
<customer id="2314">
<name>Raman deep</name>
<phone>9967345612</phone>
<purchases>30000 USD <purchases>
<address>
<street>23/25 Rajouri Garden</street>
<city>New Delhi</city>
<state>Delhi</state>
<zipcode>654321</zipcode>
</address>
</contact>
</contacts>


I hope this tutorial was brief and concise representation of the File Extension JSON .

Posted on Tuesday, June 16, 2009 by Unknown