Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery $.ajax fails in IE on cross domain calls

I am doing a cross domain request using $.ajax. It works on Firefox and Chrome, but does not issue a call on IE 7 or 8. Can anyone tell me what's wrong with the following?

  1. I have used JSON and JSONP (which I stopped using, due to some custom restrictions).
  2. I am already using Allow-access-control-origin header on my site. (Without those, Chrome and Firefox were not making successful requests.)
  3. I have already tried https://developer.mozilla.org/en/http_access_control

Code:

$.ajax({     type: 'GET',     url: "http://anotherdomain.com/Service/GetControl?id=" + zoneID,     cache: false,     contentType: "application/x-www-form-urlencoded",     async: false,     beforeSend: function (request) {         //alert('before send');         //request.setRequestHeader("X-Requested-With", "XMLHttpRequest");         //request.setRequestHeader("X-PINGOTHER", "pingpong");     } ,     success: function (data, status) {         //alert("Data returned :" + data);         //alert("Status :" + status);         if (status == "success" && data != "")             $("#" + div.id).append(data);         else             $("#" + div.id).attr("style", "display:none;");     },     error: function (XMLHttpRequest, textStatus, errorThrown) {         alert(textStatus);         alert(errorThrown);     } }); 

I have tried various tips present on multiple sites, but no luck yet.

like image 969
Furqan Hameedi Avatar asked Jul 29 '10 12:07

Furqan Hameedi


People also ask

Does AJAX support cross domain?

Cross Domain AJAX Request. A common problem for developers is a browser to refuse access to a remote resource. Usually, this happens when you execute AJAX cross domain request using jQuery Ajax interface, Fetch API, or plain XMLHttpRequest. As result is that the AJAX request is not performed and data are not retrieved.

Why is cross domain not allowed in AJAX?

Because of Same origin policy. The same-origin policy exists to prevent malicious use of resources. If there were no rules governing cross-domain script access, it would be trivial to wreak all manner of havoc on unsuspecting users.

Does Internet Explorer support AJAX?

Ajax is supported in all modern browsers.

What causes AJAX fail?

Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.


1 Answers

For IE8 & IE9 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.

IE10+ is able to do cross-domain normally like all the other browsers (congrats Microsoft... sigh)

After that the else if tests for 'XDomainRequest in window (apparently better than browser sniffing) and does the JSON AJAX request that way, other wise the ELSE does it normally with $.ajax.

Hope this helps!! Took me forever to get this all figured out originally

Information on the XDomainRequest object

// 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 & 9 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     else if (navigator.userAgent.indexOf('MSIE') != -1 &&              parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {        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);             }         });     } } 
like image 177
Mark Pieszak - Trilon.io Avatar answered Nov 07 '22 11:11

Mark Pieszak - Trilon.io