Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

how to bypass Access-Control-Allow-Origin with javascript only? WordPress

  • SOLVED

My plugin allows loading displaying gpx-track files - see a demo here: [[LINK href="http://pro.mapsmarker.com/?p=106"]]http://pro.mapsmarker.com/?p=106[[/LINK]]
The problem is when I try to load a .gpx file from another subdomain with the following code, which at least on my test site fails:

_load_xml: function(url, cb, options, async) {
if (async == undefined) async = this.options.async;
if (options == undefined) options = this.options;

var xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open('GET', url, async);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest(); //for IE
xhr.open('GET', url);
} else {
xhr.open('GET', url, async);
}
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET');

try {
xhr.overrideMimeType('text/xml'); // unsupported by IE
} catch(e) {}

xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if(xhr.status == 200){
if(xhr.responseXML){
cb(xhr.responseXML, options);
}else {
try{
var parser = new DOMParser();
cb(parser.parseFromString(xhr.response, "text/xml"), options);
} catch (e){
console.log(e);
}
}
} else {
alert(url+' could not be loaded - please check if the file exists and if it is loaded from the same domain as the website!');
}
};
xhr.send(null);
},


As far as I understand, the server from which the file should be loaded, has to support CORS, right? Or does the server which loads the file has to support CORS?
Is there a workaround to make this work on my server too?
FYI - jquery is not an option, all solutions would have to be implmented in the javascript-code above, libraries like easyXDM are also not an option.

Answers (1)

2013-08-19

Ross Wilson answers:

The most reliable way is to actually proxy your requests through a php script. When PHP uses CURL it does not require any additional cross-scripting or access control modifications.

Include something like this on the same domain you are doing the request from, and then update your code above to use point to the location of this proxy script, passing the url you want it to retrieve.
[[LINK href="http://benalman.com/projects/php-simple-proxy/"]]http://benalman.com/projects/php-simple-proxy/[[/LINK]]


Robert Seyfriedsberger comments:

thx - will try that


Robert Seyfriedsberger comments:

That will work - thx.