3

I've looked and looked but nothing quite touches this question.

I'm trying to send an XMLHttpRequest via JavaScript* in 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 shows up in the console:

Array
(
)

If something somewhere would just tell me what XMLHttpRequest.send actually 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 an XMLHttpRequest object directly until I understand exactly how it works and how PHP receives and parses it.

MackTuesday
  • 511
  • 5
  • 15
  • http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp – Raphael Rafatpanah Jul 06 '15 at 23:46
  • @Raphael THERE IT IS! I looked up XMLHttpRequest, PHP _POST, how-tos of every variety, and everything on Stack Overflow I could find. There's so much out there that tells you not quite what you need to know, it's hard to connect with just the right thing. – MackTuesday Jul 06 '15 at 23:56

2 Answers2

4

You should declare your Content-Type as application/x-www-form-urlencoded and also make a data string in the form of 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.
)

mittmemo
  • 1,962
  • 3
  • 18
  • 25
1

$_POST contains the parameters that are send via application/x-www-form-urlencoded in the request body. Since you don'thave key=value pairs, there's nothing in _POST.
Either try

xmlhttp.send("x=This+is+my+text.");

or

$post = file_get_contents('php://input');

see http://php.net/manual/de/wrappers.php.php

VolkerK
  • 92,020
  • 18
  • 157
  • 222