Category Archives: Social Apps

Skipping cross-site AJAX restrictions

Recently, I came across an issue, where I cannot do an AJAX call to my web service from my web page because they were hosted on different domains. This is a restriction put up by the browsers in accordance to the Same Origin Policy. A possible work around is to implement a server side proxy to interact with the remote site right from the server and then passing the response to AJAX requests.

I had worked with this earlier, but this time I was not in the mood to do it again. I wanted something within the page itself as implementing a proxy will increase the complexity of the whole system. So, I did some “Search” and found this awesome solution that utilizes this neat approach of referencing script src to remote site. Basically, This means the page JavaScript has to dynamically create a <script> and set its source(src) attribute to the service URL, which in turn provide the data in JSON format that is natively supported in JavaScript. Thus, we will have our response data right inside our page in JSON.

Here is a possible implementation:


function JSONData()
{
	this.serviceURL = "http://somesite.com/services/json.php";
	this.scriptEle;
	this.IdName = "script_id00";
	this.getData = function()
	{
		this.scriptEle = document.createElement("script");
		var oType = document.createAttribute("type");
		var oSrc = document.createAttribute("src");
		var oId = document.createAttribute("id");
		oType.nodeValue = "text/javascript";
		oSrc.nodeValue = this.serviceURL;
		oId.nodeValue = this.IdName;
		this.scriptEle.setAttributeNode(oType);
		this.scriptEle.setAttributeNode(oSrc);
		this.scriptEle.setAttributeNode(oId);
		this.scriptEle.src = this.serviceURL;
		document.body.appendChild(this.scriptEle);
	}

	// Use this function to reload/refresh the JSON data from the server
	this.reload= function()
	{
		this.scriptEle = document.getElementById(this.IdName);
		document.body.removeChild(this.scriptEle);
		this.getData();
	}
}

var jsonData = new JSONData();
jsonData.getData();

//change this delay according to your requirements
var delay = 10000; // let the JSON data arrive from the server

setTimeout("ShowData()",delay); //wait and let the JSON data arrive and get parsed

function ShowData()
{
	if(typeof(data)!= "undefined") //if the JSON data has been received and parsed
	{
		alert(data.FirstName + " " + data.LastName);
	}
	else
	{
		setTimeout("ShowData()",30000); // wait some more time
	}
}

in our example the JSON sent from the server will be in this form


var data = {
	FirstName : 'Sanil',
	Age : 24,
	Role: 'Software Developer',
	LastName : 'Tomar'
};

There are well defined methods that does this in jQuery. You can use the jQuery.getJSON to achieve same thing in a lot cleaner way.

Hope, this technique helps you in getting around this hurdle to access cross-site data.

♥ Happy Coding!! ♥  🙂

<digression>
Geek News: Pi (∏) to be replaced by Tau (τ) Link1 , Link2
</digression>