I am trying to send a JSON string by Javascript to a PHP script. Unfortunately it is empty. I have already checked a hundred sites on Google and SO, but I cannot find a solution to the problem. Here is what I am doing:
My HTML/Javascript:
<head>
<script type="text/javascript">
function button1_Click() {
var url = 'http://192.168.2.105/testpost.php';
var method = "POST";
var postData = {
"first": "John",
"last": "Doe"
};
var xhr = new XMLHttpRequest();
xhr.open( 'POST', url );
xhr.setRequestHeader( 'Content-Type', 'application/json' );
xhr.send( JSON.stringify(postData) );
}
</script>
</head>
<body>
<button id="button1" onclick="button1_Click()">Print</button>
</body>
And my PHP:
<?php
ob_start();
var_dump($_REQUEST);
file_put_contents('test.txt', ob_get_contents());
ob_end_close();
?>
And this is what I'm getting in test.txt:
array(0) {
}
I have no idea, why this is empty. Can you please help?
Edit: Thanks to Edgar Villegas Alvarad and Quentin
In HTML I changed the following:
xhr.setRequestHeader( 'Content-Type', 'text/plain' );
Then in PHP:
<?php
$json_data = json_decode($HTTP_RAW_POST_DATA);
ob_start();
echo $json_data->first;
file_put_contents('test.txt', ob_get_contents());
ob_end_close();
?>
And finally I get in test.txt:
John
That was what I needed.