Making Cross Domain AJAX Calls using Server Side Mediator
XMLHttpRequest is the heart of all rich and interactive AJAX based application. However some restriction apply when making request to the server. Cross-domain ajax calls to another domain is not possible due to security issues. But i came up with an idea to utilize server side request to defeat the imposed restrictions on cross domain ajax calls.
So i was thinking if there is a mediator between Domain A and Domain B sitting on the originating Domain (A) and make Server Side request to Domain B and pass the response of Domain B to Mediator which in turn pass the response to Domain A, that would do the trick. Something like this
As posted on my previous blog entries, making server side request to retrieve remote pages is not as geeky as it sounds. We can do that using HttpWebRequest Class under Namespace System.NET in ASP.NET and CURL function in PHP. So i created a generic class in ASP.NET/C# to emulate request from the originator and pass the response to the request script or page. The idea is simple.
- Script or page from Domain A send a request to the mediator which is also on Domain A with additional information like destination URL and the expected result format.
- mediator from Domain A send a request to the destination URL (Domain B) using server side call (HttpWebRequest class or CURL in PHP)
- Mediator pass the response to the script or page making the request.
- Script process the “untouched” response from mediator.
Ok before i posted this idea, of course i tested it. It worked since there is no AJAX request made outside of Domain A. However a server side http request was made from mediator to Domain B. Mediator only acts as a relay not more than that. Mediator never touched the response from Domain B, only passes them to the requestor.
Generic class in ASP.NET acting as a relay between Domain A to Domain B request
using System; using System.Net; using System.IO; ////// Mediator for Cross Domain Ajax Calls /// public class AjaxProxy { private string _methodType; private string _param; private string _expFormat; private string _targetURL; public string param{ get { return this._param; } set { this._param = value; } } public string expFormat{ get { return this._expFormat; } set { this._expFormat = value; } } public string targetURL{ get { return this._targetURL; } set { this._targetURL = value; } } public string methodType{ set { this._methodType = value; } } public AjaxProxy(string dataparam,string expformat, string targetURI){ this._param = dataparam; this._expFormat = expformat; this._targetURL = targetURI; } public string sendRequest() { HttpWebRequest request = null; request =(HttpWebRequest)WebRequest.Create( this._targetURL+’?'+this.param.Replace(”|”,”=”)); request.Method = “GET”; request.ProtocolVersion = HttpVersion.Version11; request.AllowAutoRedirect = false; request.Accept = “*/*”; request.UserAgent = “Mozilla/4.0 (compatible; MSIE 6.0;”+ Windows NT 5.1; SV1;.NET CLR 2.0.50727)”; request.Headers.Add(”Accept-Language”, “en-us”); request.KeepAlive = true; StreamReader rs = null; HttpWebResponse wr = null; string webResponseStream = string.Empty; try { wr = (HttpWebResponse)request.GetResponse(); rs = new StreamReader(wr.GetResponseStream()); webResponseStream = rs.ReadToEnd(); return webResponseStream; } catch (Exception e){ return “Error Getting Document. ” + e.Message; } } }
This class can also detect the method type use by the requesting script. We can change the method type anytime when doing server side calls to remote webpages.
Instantiating the class and invoking is member methods
//this values should be from the originating script
// that requested this page
string param=Request.Form["param"];
string format=Request.Form["format"];
string URL=Request.Form["URL"];
AjaxProxy mediator =new AjaxProxy(param,format,URL);
string response=mediator.sendRequest();
// response variable now contains the response from remote page
// we are now ready to pass this response to the requestor by writing
// the response to the browser
Response.Write(response);
)
The requestor receive the data and process. (Using jQuery to do the trick for us)
//your orginal request parameters here.
param="action=delete&id=1";
url='http://domainb.com';
format='json';
$.ajax({
type: "POST",
url: "mediator.aspx",
// append URL destinationand the expected format
data:'param='+param+'&URL='+url+'&format='+format,
dataType: "json",
success: function(r){
//process response from mediator here if the response
// is json, process as object however if the response is
// just text, just load the html response to an element.
$('#responseholder').html(r);
}
});
Notice that the original request parameters are assigned to “param” key in the querystring. here is what it looks like in a firebug console.


Request and Response is maintained on its untouched form. Mediator only acts as a relay. Basically request parameters that mediator accepts are params (containing your original parameters or querystring) , URL (the request destination or outside of your domain file or page) and finally the expected format. This can also be done in other languages, the idea is just making server side request and pass the response to the requestor script or page. As they say, “There are many ways to, well not kill a cat but lets just use cook.” There are many ways to cook :p. I hope i have successfully shared my idea with the subject.
Posted in C#/ASP.NET Programming, General Javascript Programming


![[del.icio.us]](http://genusproject.com/wp-content/plugins/bookmarkify/delicious.png)
![[DotNetKicks]](http://genusproject.com/wp-content/plugins/bookmarkify/dotnetkicks.png)
![[Digg]](http://genusproject.com/wp-content/plugins/bookmarkify/digg.png)
![[Facebook]](http://genusproject.com/wp-content/plugins/bookmarkify/facebook.png)
![[Google]](http://genusproject.com/wp-content/plugins/bookmarkify/google.png)
![[MySpace]](http://genusproject.com/wp-content/plugins/bookmarkify/myspace.png)
![[Squidoo]](http://genusproject.com/wp-content/plugins/bookmarkify/squidoo.png)
![[StumbleUpon]](http://genusproject.com/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Technorati]](http://genusproject.com/wp-content/plugins/bookmarkify/technorati.png)
![[Windows Live]](http://genusproject.com/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://genusproject.com/wp-content/plugins/bookmarkify/yahoo.png)

April 27th, 2008 at 1:23 pm
wow kuya nice naman information mo dito server side and chuvanes domain A, B … etc..side ^_^
pakai explain nga ulit sa office
nga pala I have tag you in my blog check it out and hope you post it ^_^