I am trying to send variable to php using javascript and trying to receive back and alert that variable. But $_POST['data'] doesn't get a data that I pass and $obj is always null.
If I just echo "some text"; it alerts that.
Here is my javascript code:
getMessageType('some data'); //function call
function getMessageType(str)
{
data = {'key': str};
var xhr = new XMLHttpRequest();
var url = "test.php";
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
console.log(data); //Object {key: "some data"}
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
}
Here is my PHP code:
<?php
$obj = $_POST['key'];
echo $obj;
What I am doing wrong ?
Any help is appreciated. Thanks
some datawhich I am passing when I callgetMessageTypefunction. you can see at top of code.data, so there's no way to retrieve the value by that key if you never set that key. Perhaps the string is in the POST body instead of the key/value pairs?alert()for troubleshooting., useconsole.log()instead.console.log(data);just before the send to make sure it is populated.