简体   繁体   中英

Sending data to PHP with XMLHttpRequest (vanillaJS) and reading that in php with $_POST? Undefined

I have a Javascript function which takes a parameter from HTML.

    function find(customer) {
        data = {"key":customer};
        console.log(data);
        var xhr = new XMLHttpRequest();
        var url = "test.php";
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xhr.send(data);

        xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
              console.log(xhr.responseText);
            }
        };
    }

The log produces the correct information, ie

{key:"103"}

Then in PHP, I'm trying to access this data like so:

if (isset($_POST['data'])) {
    $number = $_POST['data'];
}

echo $number;

However, PHP is throwing an error at me:

Notice: Undefined index: data in .\\test.php on line 22

This means that if(isset($_POST['key']) is returning false, and I'm not sure why. I can find plenty of information using Ajax, but not much instructing me on using standard Javascript.

EDIT:

Changed $_POST['data'] to $_POST['key'] based on comments.

Instead of index error, now receiving variable error (undefined).

Notice: Undefined variable: number in .\\test.php on line 22

This is what you are sending:

 data = {"key":customer}; xhr.send(data); 

… but when that object is converted to a string, you get: [object Object] and your actual data is lost.

You said:

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

Which claims you are sending application/x-www-form-urlencoded data to the server.

You need to convert data so it matches the content type you claim it is.

This question addresses how to do that


In addition, if one place you call your key data and the other you call it key . You have to keep using the same name throughout.

You key is actually key not data :

data = {"key":customer};

So change:

if (isset($_POST['key'])) {
    $number = $_POST['key'];
}

echo $number;

But, as you can see, $number is only defined in the if condition. So, you can define a default value

if (isset($_POST['key'])) {
    $number = $_POST['key'];
} else {
    $number = 0;
}

echo $number;

As Quentin noted, you are telling the server that the data you send is application/x-www-form-urlencoded while it's not. You can :

  • convert your data as application/x-www-form-urlencoded by using a function similar to the one linked in Quentin's answer.
    You can also use URLSearchParams if you don't care about IE/Edge support, with a nice xhr.send(new URLSearchParams(data)) . [see caniuse data ]
  • forget about $_POST , encode your data as a JSON string with a simple JSON.stringify(data) and tell your server you are sending JSON ( xhr.setRequestHeader("Content-Type", "application/json") , then get your array with $data = json_decode(file_get_contents('php://input'), true);

Try var_dump($_POST); exit; And you will see that there is not any data key in POST array , instead you have 'key' key so instead of $_POST['data'] write $_POST['key']

try to print all post data first, you will get actual name which is being posted

print "<pre>";
print_r($_POST);

in your PHP code, this will output the posted data with the actual name of parameter you are getting just use that one instead $_POST["data"] i am assuming you have the value in $_POST["key"] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM