I'm just writing my first JavaScript code today. On my local machine I'm running:
<!DOCTYPE html>
<html>
<head>
<title>Admin</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function myTable()
{
var http = new XMLHttpRequest();
var url = "MYSERVERADDRESS/login.php";
var params = "username=ABC&password=123";
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
document.write("state = " + http.readyState + ", status = " + http.status);
if(http.readyState == 4 && http.status == 200) {
document.write(http.responseText);
}
}
http.send(params);
}
</script>
</head>
<body>
<div>Test Page</div>
<script>
myTable();
</script>
</body>
</html>
When I run the above, the http.status
return 0
, so the document write never takes place. Why is this happening?
On reading around on the matter I understand that XMLHttpRequest
will not by default allow cross domain posts for security reasons. This could be the reasons since I'm running the Javascript on my local host (laptop), and my server MYSERVERADDRESS
is a different domain... Could this be a CORS problem?
But an online article suggested to use this in the header to overcome this:
http.setRequestHeader('X-PINGOTHER', 'pingpong');
which did not work. I also read that I need to let my server know that I can allow access to the outside, so I also included this in my login.php
endpoint:
//Set Access-Control-Allow-Origin with PHP
header('Access-Control-Allow-Origin: *', false);
but that didn't work either. (By the way I know the wildcard *
is very bad here, but for testing I just wanted to try it for a quick result)
I'm a bit stumped from hereon in. Can anyone explain what I'm doing wrong please?
Thanks to the @Quentin, this is my browser's developer console output:
:8383/favicon.ico:1 GET http://localhost:8383/favicon.ico
net::ERR_EMPTY_RESPONSE
index.html:1 Failed to load MYSERVERADDRESS/login.php: Request header field X-PINGOTHER is not allowed by Access-Control-Allow-Headers in preflight response.
VM1389:207 Uncaught TypeError: target.hasAttribute is not a function
at MutationObserver.<anonymous> (<anonymous>:207:29)