PHP JavaScript – Cross Domain XMLHttpRequest

cross-domainjavascriptphpsame-origin-policyxmlhttprequest

I am writing this javascript that will be used on several other domains which calls a php script(only on my domain) to return an array. I am using xmlhttp and it works great when testing on my domain, but as soon as the javascript is placed or called from a separate domain it completely breaks. Anybody know how to make this request cross-domain?

Note: I had to perform a weird little hack to allow me to make two separate calls and make sure that they were both returned before processing. Anyways this does work perfectly every time on my domain.

This is tin the javascript file that calls my php code for the array

function getUrls(){
if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    xmlhttp2 = new XMLHttpRequest();
}
else {
    // code for IE5 and IE6
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    // code for IE5 and IE6
    xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
        parsedJSONurls = JSON.parse(xmlhttp.responseText);
        xmlhttp2.open("GET", "http://mydomain.com/connect.php?q=companies", true);
        xmlhttp2.send();
    }
}
xmlhttp2.onreadystatechange = function(){
    if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
        parsedJSONcompanies = JSON.parse(xmlhttp2.responseText);
        runLoop(parsedJSONurls, parsedJSONcompanies);
    }
}
xmlhttp.open("GET", "http://mydomain.com/connect.php?q=urls", true);
xmlhttp.send();

}

Best Answer

Try adding this header to your connect.php file

header('Access-Control-Allow-Origin: http://domain1.com, http://domain2.com');

If you want to permit all domains instead of a whitelist

header('Access-Control-Allow-Origin: *');

https://developer.mozilla.org/en/http_access_control

Related Question