在PHP中用$ .ajax回显$ _POST

I'm trying to echo $_POST with $.ajax in PHP with no success. In Xdebug I see the $_POST get the right value and executing the echo $_POST line, but I keep getting the else output clause. Also in chrome I see the headers that are sent valid. All the code is in the same page index.php.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery.post demo</title>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>

<button type="button" id="but">Click Me!</button>

<script>
    $('#but').click(function() {
        $.ajax({
            type: "POST",
            url: "index.php",
            data: {name: "John"},
            success: function() {
                alert('success');
            }
        });
    });
</script>
</body>
</html>

<?php

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    echo $_POST['name'];
} else {
    echo "Nothing to Show";
}
?>

At the moment the whole page is being returned in response to your AJAX request; HTML and all. You're also not retrieving the value returned from the request in your JS code, to do that you just need to accept a parameter on your success handler. Try this:

In it's own file, say foo.php:

<?php
    if ($_SERVER['REQUEST_METHOD'] == "POST") {
        echo $_POST['name'];
    } else {
        echo "Nothing to Show";
    }
?>

Then in your HTML:

<script>
    $('#but').click(function() {
        $.ajax({
            type: "POST",
            dataType: 'text', // to ensure jQuery doesn't try to deserialise the repsonse
            url: "foo.php",
            data: { name: "John" },
            success: function(response) {
                console.log(response.trim()); // = 'John'
            }
        });
    });
</script>

Ajax will return a response and you can use that response to display. It will not work on the same page.

Try as below :

main.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery.post demo</title>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<button type="button" id="but">Click Me!</button>
<div id="result"></div>
<script>
    $('#but').click(function() {
        $.ajax({
            type: "POST",
            url: "test.php",
            data: {name: "John"},
            success: function(data) {
                alert('success');
                $('#result').html(data);
            }
        });
    });
</script>
</body>
</html>

test.php

<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    echo $_POST['name'];
} else {
    echo "Nothing to Show";
}
?>