In php, how do I get the text/plain value of send() method of XMLHttpRequest

I have no idea how to get the "Hello World!" in PHP for the following Javascript codes. I know I can use $_POST[''] if the content-type was "application/x-www-form-urlencoded", but not for "text/plain".

var xhr = new XMLHttpRequest();
xhr.open('POST', 'example.php', true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('Hello World!');

Answers


This PHP will read the raw data from the request body:

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

Line 3:

xhr.setRequestHeader('Content-Type', 'text/plain');

isn't required as posting plain text will set the content type to text/plain;charset=UTF-8 http://www.w3.org/TR/XMLHttpRequest/#the-send-method


There are a number of things wrong with your request. You can’t POST data without using application/x-www-form-urlencoded. Secondly, “Hello World!” isn't escaped or attached to a variable.

Following is the javascript code to POST data to the server.

var xhr = new XMLHttpRequest();
var params = 'x='+encodeURIComponent("Hello World!");
xhr.open("POST", 'example.php', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}
xhr.send(params);

You can access this with $_POST['x'] in PHP.

Alternatively, you use $_GET['x'] by using the following code.

var xhr = new XMLHttpRequest();
var params = encodeURIComponent("Hello World!");
xhr.open("GET", 'example.php?x='+params, true);
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}
xhr.send(null);

GET is more in line with the idea of using Content-type: text/plain.


You might try http_get_request_body (http://php.net/manual/en/function.http-get-request-body.php)


Need Your Help

How does requests module work?

python python-requests

I'm looking at the requests module, and I don't understand how the method requests.get() can be invoked.

Problems with PayPal API Http call

c# asp.net paypal httpwebrequest httpwebresponse

I've integrated an option for users to pay via PayPal their online shopping on the web shop that I'm creating. The problem came up suddenly when I started to get this error: