Ramandeep Singh Nanda
Published

Thu 21 March 2013

←Home

Cross Domain Ajax Requests

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. .. code-block:: js

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. .. code-block:: js

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. .. code-block:

<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>

Go Top
comments powered by Disqus