I have some simple code trying to make an ajax request. I tried using a .txt file and found a CORS error. I then tried using a php file using header("Access-Control-Allow-Origin: *"); because I heard this is the easiest way to allow all ajax calls on any browser. I have looked through many SO posts and have googled everywhere, and cant seem to find a solution. Here are my files. I will include the .txt file, but i already understand why that file isnt working.
ajax-1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button">Get Text File</button>
<br><br>
<div id="text">
</div>
<script>
//create event listener
document.getElementById('button').addEventListener('click', loadText);
function loadText() {
//create an object
const xhr = new XMLHttpRequest();
//open - type, url/file, async t/f
xhr.open('get', 'sample.php', true);
console.log('READYSTATE: ', xhr.readyState);
//OPTIONAL - used for loaders
xhr.onprogress = function () {
console.log('READYSTATE: ', xhr.readyState);
}
xhr.onload = function () {
console.log('READYSTATE: ', xhr.readyState);
if (xhr.status == 200) {
// console.log(this.responseText);
document.getElementById('text').innerHTML = this.responseText;
} else {
document.getElementById('text').innerHTML = 'Not Found';
}
}
xhr.onerror = function () {
console.log('request error');
}
//sends request
xhr.send();
}
</script>
</body>
</html>
sample.php
<?php
header("Access-Control-Allow-Origin: *");
echo "Some Lorem ipsum text";
?>
sample.txt
lorem ipsum
Here is what the chrome console shows
READYSTATE: 1
ajax1.html:1 Access to XMLHttpRequest at 'file:///Users/macbookuser/Desktop/traversy/ajax/sample.php' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. ajax1.html:46 request error ajax1.html:56 GET file:///Users/macbookuser/Desktop/traversy/ajax/sample.php net::ERR_FAILED