There are several errors in your request. You can use tSTST data without using application/x-www-form-urlencoded . Secondly, "Hello World!" not escaped or bound to a variable.
Below is the javascript code for the 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'] 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 .
source share