I am doing this the hard way and _POST is empty
I looked and looked but nothing touches on this question.
I am trying to submit XMLHttpRequest
via JavaScript * to Chrome. Here is my page:
<!DOCTYPE html>
<html>
<head>
<title>ROAM</title>
<script>
function post_something() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', "post_test.php", true);
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
xmlhttp.send("This is my text.");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<table>
<tr><td><input type="button" value="POST a thingy"
onclick="javascript:post_something()">
</input>
</td></tr>
</table>
</body>
</html>
Here is my PHP:
<?php
print_r($_POST);
/>
This is displayed in the console:
Array
(
)
If something somewhere just tells me what XMLHttpRequest.send really does under the hood, what exactly it sends, how PHP parses it, and what PHP expects, I could solve this dumb thing myself.
* Please understand, I don't want to use a form or jQuery. I want to work with the XMLHttpRequest object directly until I understand how it works and how PHP gets and parses it.
source to share
You have to declare yours Content-Type
as application/x-www-form-urlencoded
and also create a data line in the form key1=value1&key2=value2&key3=value3
.
function post_something() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', "post_test.php", true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = "text=This is my text.&text2=This is my second text.";
xmlhttp.send(encodeURI(data));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
}
}
Output:
Array
(
[text] => This is my text.
[Text2] => This is my second text.
)
source to share