I am running an html file on my localhost. I am accessing a php file on my server.
Javascript being run on localhost:
var url = "http://www.chartmygolf.com/_TEST_DELETE/exclude.php";
var method = "GET";
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function (data) {
var text = xhr.responseText;
alert('Response: ' + text);
};
xhr.onerror = function (data) {
alert('Woops, there was an error making the request.');
};
xhr.send();
The php on my server www.mysite.com:
<?php
$referrer = $_SERVER['HTTP_REFERER'];
$parts = parse_url($referrer);
$domain = $parts['host'];
header("Access-Control-Allow-Origin: http://" . $domain);
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$arr = array("181K2", "4V419");
echo json_encode($arr);
?>
In Chrome and Edge it goes into alert('Woops, there was an error making the request.');
Edge Error:
SEC7120: Origin http://localhost:8080 not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80700013, Could not complete the operation due to error 80700013.
Chrome Error:
XMLHttpRequest cannot load http://www.chartmygolf.com/_TEST_DELETE/exclude.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
This is driving me insane. I have tried ajax and now this method and I get inconsistent results. I have read loads of threads here on stackoverflow and none of the answers work. (However, these threads seem to be ages old.)
Note: I get the same error if I use
header("Access-Control-Allow-Origin: *");
Please help. I am losing all grip on my sanity.
OK. Found it. I do not have access to php settings on my server. It is a Windows server.
Putting this into a web.config
file in the directory where the php script is does the trick.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
If you are not on a windows server, you will need to do the .htaccess
exquivalent of the above.