Constan7ine Constan7ine - 4 months ago 19
Javascript Question

$_POST is empty after simple AJAX POST

I've simplified my code to try isolate the issue, but I can't seem to get anything from the $_POST variable in php after javascript sends a POST request. Have a look at this:

<!DOCTYPE html>
<html>
<body>

<h2>AJAX Test</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "submit.php?name=david", true);
xhttp.send();
}
</script>

</body>
</html>


And this is submit.php

<?php
var_dump($_POST);
if(!empty($_POST))
{
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);

$output = json_encode(array('type'=>'message', 'text'=>$name.', thank you for your email!'));
die("$output");
}
?>


When I press the button the response is simply:

array(0) { }


The empty state of the _POST variable.

I'm running this on a default setup MAMP server, with nothing changed. What's wrong?

Answer

You need to set the content type:

xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.open("POST", "submit.php?name=david", true);
xhttp.send();

By the way, I'm not sure your

?name=david

would work...