As I attempt to utilize Ajax to retrieve data from my website using a script that should be able to execute from any location, the Ajax code within my script is structured like this:
var ajax = new XMLHttpRequest();
ajax.open('GET', 'http://mywebsite.com/page?i=2&json', true);
ajax.onreadystatechange = function() {
if (ajax.status == 200) {
console.log(JSON.parse(ajax.responseText));
}
else
console.log('Could not connect.');
}
ajax.send();
However, upon execution, I encounter the following error:
XMLHttpRequest cannot load . Origin is not allowed by Access-Control-Allow-Origin.
Within the script on my website, the following lines are incorporated within the page:
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
Despite this, the error persists. It is essential for the page on my website to be accessible from any internet domain via Ajax, as my script serves as an extension meant for universal usability.
EDIT: I managed to resolve this issue by setting the 'withCredentials' attribute on the Ajax object to true, and on my server, sending back the Access-Control-Allow-Credentials header set to true. Additionally, within my script, I passed the domain so it could be included in the Access-Control-Allow-Origin header on my server script. Using the wildcard * did not yield successful results. As of now, this has only been tested in Chrome.