Skip to content

Instantly share code, notes, and snippets.

@abhilash0001
Created August 1, 2014 18:41
Show Gist options
  • Save abhilash0001/5ad7ee246eb1813a9af3 to your computer and use it in GitHub Desktop.
Save abhilash0001/5ad7ee246eb1813a9af3 to your computer and use it in GitHub Desktop.
Cross domain ajax call - IE9+, Chome, Firefox, etc
/*********************************************************************************
Cross domain ajax call
IMPORTANT:
----------
If the webservice you are calling uses http, then the page you are calling the
function below should be http
If the webservice you are calling uses https, then the page you are calling the
function below should be https
In other words: http->http and https->https
**********************************************************************************/
// How to use it
crossDomainAjax(url, function (data) {
// Success code
});
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);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment