user3105607
user3105607

Reputation: 369

Retrieving AJAX data in PHP

I need to use the xhr.send(VALUE) to send the data in AJAX. How do I get this data in a PHP file?

JS:

window.onload = function() {
    var value = 'hello';
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        } else {
            alert("no");
        }
    }
    xhr.open('POST', 'json.php', true);
    xhr.send(value);

}

Upvotes: 0

Views: 176

Answers (3)

Alex Shilman
Alex Shilman

Reputation: 1547

Try this, replace your xhr.send with

JS

 xhr.send('value='+value);

PHP

echo($_POST['value']);

Upvotes: 0

MrHunter
MrHunter

Reputation: 1900

If you want to see the $_POST variables on the PHP page you can use this code to display them all so you can visually see their keys and values

echo "<pre>";
print_r($_POST);
echo "</pre>";

From there you will know how to use the data in any file. You can do the same thing with $_GET

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227200

You are just sending a string to the PHP file. You are not sending it as a query string or with a content type, so PHP doesn't populate the $POST array.

You can try to read the raw post data:

$post = file_get_contents('php://input');
echo $post; // hello

Or, if you want PHP to populate $_POST, you need to do some extra steps in your JavaScript.

window.onload = function() {
    var value = 'hello';
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        } else {
            alert("no");
        }
    }

    xhr.open('POST', 'json.php', true);

    // Tell the server you are sending form data
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    // Send it as a query string
    xhr.send('value='+value);
}

Then in your PHP, you can access $_POST['value'].

echo $_POST['value'];  // hello

Upvotes: 1

Related Questions