Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1546
  • Last Modified:

CORS - IE8 and up with jquery

At some point I had this working, but for the life of me it is not working now and I was wondering if someone could take a look at this, and tell me what it is that I am doing wrong.


I have two domains

productname.ourdomain.com
Which will be the source domain for all interactions with the site that the user will see.

api.ourdomain.com
Is our restful service and sends json back and forth.



User logins into the site and is brought to the home, and the current patient list is pulled into the home page, and this is done through the following call.

function loadPatientList(site_id) {
    var wcfUrl = getSiteRestFullUrl();
    
    var strUrl = wcfUrl + "sites/" + site_id + "/patients";
    
    $.ajaxSetup({ 'dataType': 'json' })
    $.support.cors = true;
    $.ajax({
        type: "GET",
        url: strUrl,
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("sidw-token", getToken());
        },
        
        success: function (msg) {
            //alert(JSON.stringify(msg[0]));
            successDisplayPatientList(msg);
        },
        error: function (msg) {
            alert(JSON.stringify(msg));
            
        }
    });
}

Open in new window


so the url in the above js function would be api.ourdomain.com/sites/188/patients and this would pull back the json and display on the page.

On every browser (otherthan IE8 and IE9) this is working perfectly, but as soon as I hit IE then it blows up.

I have set the correct options to allow cross browser to work in the global.asax of the wcf service code.

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, sidw-token");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

                HttpContext.Current.Response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");


                    
                HttpContext.Current.Response.End();
            }
        }

Open in new window


Any help you can give on this would be appreciated. Thanks.
0
JDEE8297
Asked:
JDEE8297
  • 2
  • 2
2 Solutions
 
Ahmed HusseinCommented:
For IE8+ you need to use XDomainRequest (XDR). If you look below you'll see it's in a sort of similar formatting as $.ajax. As far as my research has got me I can't get this cross-domain working in IE6 & 7 (still looking for a work-around for this). XDR first came out in IE8 (it's in IE9 also). So basically first, I test for 6/7 and do no AJAX.

// call with your url (with parameters) 
// 2nd param is your callback function (which will be passed the json DATA back)

crossDomainAjax('http://www.somecrossdomaincall.com/?blah=123', function (data) {
    // success logic
});

function crossDomainAjax (url, successCallback) {

    // IE8+ only Cross domain JSON GET request
    if ('XDomainRequest' in window && window.XDomainRequest !== null) {

        var xdr = new XDomainRequest(); // Use Microsoft XDR
        xdr.open('get', url);
        xdr.onload = function () {
            var dom  = new ActiveXObject('Microsoft.XMLDOM'),
                JSON = $.parseJSON(xdr.responseText);

            dom.async = false;

            if (JSON == null || typeof (JSON) == 'undefined') {
                JSON = $.parseJSON(data.firstChild.textContent);
            }

            successCallback(JSON); // internal function
        };

        xdr.onerror = function() {
            _result = false;  
        };

        xdr.send();
    } 

    // IE7 and lower can't do cross domain
    // I'm using jQuery's $.browser (deprecated in 1.9 of course)
    // You could change this to navigator.userAgent, whatever works for you of course

    else if ($.browser.msie && parseInt($.browser.version, 10) <= 7) {
       return false;
    }    

    // Do normal jQuery AJAX for everything else          
    else {
        $.ajax({
            url: url,
            cache: false,
            dataType: 'json',
            type: 'GET',
            async: false, // must be set to false
            success: function (data, success) {
                successCallback(data);
            }
        });
    }
}

Open in new window


~AG
0
 
JDEE8297Author Commented:
will this work for a post and also allow me to pass something in on the header of the request?
0
 
Ahmed HusseinCommented:
Here's how you can send a POST request using XDomainRequest:

var xdr;
function err() {
    alert('Error');
}
function timeo() {
    alert('Time off');
}
function loadd() {
    alert('Response: ' +xdr.responseText);
}
function stopdata() {
    xdr.abort();
}   
xdr = new XDomainRequest();
if (xdr) {
    xdr.onerror = err;
    xdr.ontimeout = timeo;
    xdr.onload = loadd;
    xdr.timeout = 10000;
    xdr.open('POST','http://example.com');
    xdr.send('foo=12345');
    //xdr.send('foo=<?php echo $foo; ?>'); to send php variable
} else {
    alert('XDR undefined');
}

Open in new window


But unfortunately you can't send custom headers. using XDR.

~AG
0
 
JDEE8297Author Commented:
thanks
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now