7

I want to send a POST request to a PHP script. I am using Axios:

axios.post('inc/vote.php', {
    id: this.selected,
}) .then(function (response) {
    console.log(response);
});

In the PHP file I am trying something like this to retrieve that id variable from axios:

$id = $_POST['id'];

But seems it is not doing anything.

What is the correct way to retrieve variables from the request?

Marco
  • 7,007
  • 2
  • 19
  • 49
Rakesh Kohali
  • 275
  • 2
  • 5
  • 17
  • `$id` is empty or returns undefined variable `id`? – Rotimi Mar 02 '18 at 13:48
  • 4
    Use `$_POST['id'];`. you forgot one `'`. What you can do also is `var_dump($_POST);` to see if your $_POST contains the parameters you expect to receive. – Nic3500 Mar 02 '18 at 13:49
  • This is a duplicate. It's not related to the OP's initial typo (already fixed). Axios is _not_ sending URL encoded requests by default, and so $_POST will not be populated. See the documentation and original post. – Boaz Mar 02 '18 at 14:04
  • @Akintunde007 it is showing Undefined index: id – Rakesh Kohali Mar 02 '18 at 14:16

1 Answers1

24

Axios sends data as a JSON inside request body not as a Form Data. So you can't access the post data using $_POST['id'].

Frontend Solution

To be able to access data using $_POST['id'] you have to use FormData as the following:

var form = new FormData();
form.append('id', this.selected);
axios.post('inc/vote.php', {
    form
  }) .then(function (response) {
    console.log(response);
  });

Backend Solution if you are interested in getting the request body as associative array you can use:

$data = json_decode(file_get_contents("php://input"), TRUE);
$id = $data['id'];