Blogsite that talks about web Programming experiences,techniques and ideas for ASP,PHP,ASP.NET and Javascript.

Making Cross Domain AJAX Calls using Server Side Mediator

April 26th, 2008 by Roy L. `dshiznitz Besiera

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.

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

Cross-domain ajax calls using a mediator

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.

cross-domain response from a firebug console

cross-domain response from 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

4 Responses

  1. Aice Nice Concepts

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

  2. Khalid

    You explain a complaxe concept in vary easy manner by using demographic method. your define problem stage first and then solution in visible way that made me clear about that concept

    Thanks for good article

  3. manoj

    where we use this jQuery??
    How its Call??

    Can any one Ans this

  4. Anand Sharma

    Your code is fantastic.
    It solve my lots of tension.
    Thanks for such a nice code.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.