Click here to Skip to main content
13,045,540 members (73,423 online)
Click here to Skip to main content
Add your own
alternative version


15 bookmarked
Posted 25 Apr 2011

AJAX Cross-Origin HTTP request

, 24 Nov 2011
Rate this:
Please Sign up or sign in to vote.
Describes a standard way to implement Cross-Origin Ajax request other than JSONP or something else.


Cross-Origin HTTP request (A.K.A. Cross-Domain AJAX request) is an issue that most web developers might encounter, according to Same-Origin-Policy, browsers restrict client JavaScript in a security sandbox, usually JS cannot directly communicate with a remote server from a different domain. In the past developers created many tricky ways to achieve Cross-Domain resource request, most commonly using ways are:

  1. Use Flash/Silverlight or server side as a "proxy" to communicate with remote.
  2. JSON With Padding (JSONP).
  3. Embeds remote server in an iframe and communicate through fragment or, refer here.

And so on..

Those tricky ways have more or less some issues, for example JSONP might result in security hole if developers simply "eval" it, and #3 above, although it works, both domains should build strict contract between each other, it neither flexible nor elegant IMHO:)

W3C had introduced Cross-Origin Resource Sharing (CORS) as a standard solution to provide a safe, flexible and a recommended standard way to solve this issue. 


From a high level we can simply deem CORS is a contract between client AJAX call from domain A and a page hosted on domain B, a tipical Cross-Origin request/response would be:

DomainA AJAX request headers

User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
Accept-Language en-us;
Accept-Encoding gzip, deflate
Keep-Alive 115

DomainB response headers

Cache-Control private /> Content-Type application/json; charset=utf-8
Content-Length 87
Proxy-Connection Keep-Alive
Connection Keep-Alive

The blue parts I marked above were the kernel facts, "Origin" request header "indicates where the cross-origin requestor preflight request originates from", the "Access-Control-Allow-Origin" response header indicates this page allows remote request from DomainA (if the value is * indicate allows remote requests from any domain).

As I mentioned above, W3 recommended browser to implement a "preflight request" before submitting the actually Cross-Origin HTTP request, in a nutshell it is an HTTP "OPTIONS" request:


If foo.aspx supports OPTIONS HTTP verb, it might return response like below:

HTTP/1.1 200 OK
Date: Wed, 01 Mar 2011 15:38:19 GMT
Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
Access-Control-Allow-Headers: X-Requested-With
Access-Control-Max-Age: 1728000
Connection: Keep-Alive
Content-Type: application/json

Only if the response contains "Access-Control-Allow-Origin" AND its value is "*" or contain the domain who submitted the CORS request, by satisfying this mandtory condition browser will submit the actual Cross-Domain request, and cache the result in "Preflight-Result-Cache".


Let's take a look at server side code samples below (ASP.NET and PHP):


protected void Page_Load(object sender, EventArgs e)
    String data = String.Empty;
    String returnJSONStr = String.Empty;

    switch (Request.HttpMethod)
        case "GET":
            data = Request.QueryString["Data"];
            returnJSONStr = "{\"Data\":\"Hi remote friend, you tried to passed me data: *" + data + "* through HTTP GET.\"}";
        case "POST":
            data = Request.Form["Data"];
            returnJSONStr = "{\"Data\":\"Hi remote friend, you tried to POST some mock data: *" + data + "* to me.\"}";
        case "OPTIONS":

    if (String.IsNullOrEmpty(data))
        Response.AddHeader("Access-Control-Allow-Origin", "*");
        Response.ContentType = "application/json";

private void returnBadRequestResponse()
    Response.StatusCode = 400;
    Response.ContentType = "application/json";
    Response.Write("{\"Error\":\"Bad HTTP request type!\"}");



        $fakeData=new FakeData();
        $fakeData->Data="Hi remote friend, you tried to POST some mock data: *"+data+"* to me.";
        $fakeData->Time=new DateTime("now");
        $fakeData=new FakeData();
        $fakeData->Data="Hi remote friend, you tried to passed me data: *"+data+"* through HTTP GET.";
        $fakeData->Time=new DateTime("now");

    header('Content-type: application/json');
    $jsonStr= json_encode($fakeData);

function RaiseError()
    header("Status: 405 Method Not Allowed");

/*Classes definition*/
class FakeData
    public $Data;
    public $Time;

Then client Ajax call code:

var cor = null; // cor stands for Cross-Origin request

if (window.XMLHttpRequest) {
    cor = new XMLHttpRequest();
//else if (window.XDomainRequest) {
    //cor = new XDomainRequest();
else {
    alert("Your browser does not support Cross-Origin request!");

cor.onreadystatechange = function () {
    if (cor.readyState == 4) {
        document.getElementById('lbl').innerHTML = cor.responseText;

var data = 'Some fake data';
if (method == 'POST') {'POST', '', true);
    cor.withCredential = "true";
    cor.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    cor.send('Data=' + data);
else if (method == 'GET') {'GET', '' + data, true);
    cor.withCredential = "true";

The JS code works for all mainstream browsers (IE8+, FF 3.6+, Chrome 8+), I didn’t use XDomainObject which introduced in IE8 because XMLHttpRequest is already supported by IE8+, FF and Chrome, Safari, in additional XDR seems have a lot of restrictions (refer:


Cross-Origin Resource Sharing provides a safe, flexible and a standard way for web developers to achieve Cross-Origin communication, maybe it is time to forget those tricky or inelegant ways like JSONP, Flash/Silverlight/server bridge or even and so on:)



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Wayne Ye
Software Developer (Senior) SAP Labs Shanghai
China China
Wayne is a software developer, Tech Lead and also a geek. He has more than 6 years' experience in Web development(server: ASP.NET (MVC), Web Service, IIS; Client: HTML/CSS/JavaScript/jQuery/AJAX), Windows development (Winform, Windows Service, WPF/Silverlight, Win32 API and WMI) and SQL Server. Deep understanding of GOF Design Patterns, S.O.L.i.D principle, MVC, MVVM, Domain Driven Design, SOA, REST and AOP.

Wayne's Geek Life

Infinite passion on programming!

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Rene Pilon1-May-11 12:41
memberRene Pilon1-May-11 12:41 
Nice going Wayne. 5.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170713.1 | Last Updated 24 Nov 2011
Article Copyright 2011 by Wayne Ye
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid