1

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, i.e.

{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

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Karim
  • 271
  • 2
  • 11
  • PHP won't receive a parameter for 'data', as 'data' as you are referring to it on the javascript side of things here maps over to the $_POST superglobal on the server, so $data = $_POST. So you should be able to just read this as `$_POST['key'];` – Jack hardcastle Dec 03 '18 at 14:59
  • @Jackhardcastle Correct. Little mistake but after fixing it, I still have the same issue. – Karim Dec 03 '18 at 15:03
  • Please dont change code as it makes comments/answers look foolish. Instead add and EDIT and make the changes – RiggsFolly Dec 03 '18 at 15:06
  • Actually the error has changed. Now it's undefined variable. – Karim Dec 03 '18 at 15:06
  • And ALWAYS show us the complete error message – RiggsFolly Dec 03 '18 at 15:07
  • Notice: Undefined variable: number in .\test.php on line 22 – Karim Dec 03 '18 at 15:08
  • Thats because ... if `$_POST['key']` is no set, you Never Define or Set `$number;` – RiggsFolly Dec 03 '18 at 15:10
  • This makes sense. However, why wouldn't my data be passed from JS to PHP? Where is it failing? Inside javascript, the data variable contains the information. Inside PHP, it's saying that $number = 0 (when using else statement) or undefined (without else statement). I just don't understand why the value isn't being passed through correctly. – Karim Dec 03 '18 at 15:16

5 Answers5

1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Interesting. So if it was text/html and data = number, it should work? – Karim Dec 03 '18 at 15:17
  • PHP does not understand the `text/plain` MIME type so wouldn't even try to parse it to populate `$_POST` (and `plain/text` is not a standard MIME type at all). – Quentin Dec 03 '18 at 15:18
  • Apologies. I'm still learning PHP (only a few weeks old). Could you point me to a resource that explains how I should send this data? – Karim Dec 03 '18 at 15:20
  • @Karim — I did. Click the link in this answer. – Quentin Dec 03 '18 at 15:20
  • So, if I'm always going to be sending a 3 digit string, would it be easier (instead of converting the data), to just send the string version (not the key:value)? For example, data = string(number). I know this may not be correct syntax or if you can even type-cast as in python. I'm just thinking conceptually right now. – Karim Dec 03 '18 at 15:28
  • @Karim — No, because then you need to read the raw request body in PHP. If you know it is just going to be a number, you could *manually* construct the URL encoded data. `"key=" + number` – Quentin Dec 03 '18 at 15:29
0

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;
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
  • Correct. Sorry. However, I still have the same issue after fixing it. – Karim Dec 03 '18 at 15:02
  • A different issue, sorry. Notice: Undefined variable: number in .\test.php on line 22 – Karim Dec 03 '18 at 15:09
  • Updated, take a look. – Felippe Duarte Dec 03 '18 at 15:10
  • After defining else, it's returning 0 (as expected since we know the if condition was failing). My question, I suppose, is why is it failing? Based on the above code, why isn't the value of number getting passed correctly to PHP? – Karim Dec 03 '18 at 15:13
0

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);
sylbru
  • 1,461
  • 1
  • 11
  • 19
  • PHP will not automatically populate `$_POST` with JSON encoded data. If you do that you also need to write server-side code to read the raw request body and parse it. – Quentin Dec 03 '18 at 15:25
  • True, I forgot about that, I'll edit my answer. In the end it's just a matter of how and where you want to do the conversion, I just think I prefer a simple `JSON.stringify` in the browser with a simple `json_decode` in the server (especially with frameworks like Slim doing this out-of-the-box). – sylbru Dec 03 '18 at 15:33
-1

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']

-1

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

Ashfaque Ali Solangi
  • 1,883
  • 3
  • 22
  • 34