I am trying to send the post request to my PHP file but it is saying undefined index.
my js code -
document.getElementById("btn1").addEventListener('click', xh );
function xh(){
xhr = new XMLHttpRequest();
//xhr.open('GET', 'req.php?msg=hello bro', true);
xhr.open('POST', 'req.php');
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
xhr.onprogress = function () {
// document.getElementById("loading").classList.remove("dis");
}
xhr.onload = function () {
console.log(this.responseText);
}
xhr.send("msg=hello");
}
my PHP code -
<?php
if(isset($_POST['msg'])){
echo "set";
}
else{
echo "not set";
}
?>
I also tried the server request method but it didn't work
it is showing not set, and if I try to echo the $_POST['msg']; it says undefined index 'msg'
Instead of
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
you want to set the request header
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Read more about XHR. The present approach it to use fetch() though.
fetch("req.php", {
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: "msg=hello"
}).then(response => response.text())
.then(console.log)