Solved

CORS - IE8 and up with jquery

Posted on 2013-05-28
4
1,451 Views
Last Modified: 2013-05-29
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
Comment
Question by:JDEE8297
  • 2
  • 2
4 Comments
 
LVL 4

Assisted Solution

by:Ahmed Hussein
Ahmed Hussein earned 315 total points
ID: 39202624
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
 

Author Comment

by:JDEE8297
ID: 39202704
will this work for a post and also allow me to pass something in on the header of the request?
0
 
LVL 4

Accepted Solution

by:
Ahmed Hussein earned 315 total points
ID: 39202745
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
 

Author Closing Comment

by:JDEE8297
ID: 39206432
thanks
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now