Constan7ine Constan7ine - 1 year ago 89
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>

<h2>AJAX Test</h2>

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

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

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


And this is submit.php

$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);

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

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 Source

You need to set the content type:

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

By the way, I'm not sure your


would work...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download