Am trying to do an Ajax call from my local computer using Lampp server, and it keeps giving this error.
Access to XMLHttpRequest at 'file:///opt/lampp/htdocs/AjaxProject/sample.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. loadText @ trying.html:27
<!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>Ajak tutorials</title>
</head>
<body>
<button id="button">Change text</button>
<p id="text">Let Ajax change this </p>
<script>
document.getElementById('button').addEventListener('click',loadText);
function loadText()
{
var xhr=new XMLHttpRequest();
xhr.open('GET','sample.txt',true);
xhr.onload=function(){
if(this.status==200){
document.getElementById('text').innerHTML=this.responseText;
}else if(this.status==404){
document.getElementById('text').innerHTML="Not found";
}
}
xhr.send();
}
</script>
</body>
</html>
check file and folder permissions. Also, you sometimes need to add the "txt" extension in htaccess on the line of permitted extensions that can be executed by the web browser.
some installations might have this in htaccess, that you might have to modify:
IndexIgnore *.zip *.txt
Also, sometimes, if the file navigation is turned off, it would disable the file:/// protocal. check for:
Options -Indexes
Also, setting a header might cause the browser to handle the request better, so, right after the xhr.open() line:
xhr.setRequestHeader("Content-type", "text/plain");