1

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?

2 Answers 2

1

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...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, but this doesn't seem to help.
1

or simply you can use ajax method in jquery

$(document).ready(function() {
    $(document).on("submit", "#formID", function(e) {

        $.ajax({
            type: "POST",
            url: "WhereToPost.php",
            contentType: false,
            cache: false,
            processData: false,
            async: true,
            data: new FormData(this),
            success: function(data) {
                alert(data);
            },
            error: function() {
                alert("Error Handeling Here");
            }

        });
        e.preventDefault();
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.