22

I want to send a POST request to my PHP file to handle it and store the data in the database.. I'm pretty stuck at it since $_POST stays empty whatever I try..

Can someone help me sending a post request and help me how to handle it ?

My axios request:

// Performing a POST request
axios.post('dev/api/post.php',{ text: text, unk: unk})
  .then(function(response){
      console.log(response);
}).catch(function (error) {
      console.log(error);
});  

And this is what I kinda tried in PHP, some code is commented out because not sure if it worked..

if(isset($_POST) && !empty($_POST)){
/*  
$jsonReceiveData = json_encode($_POST);
$json_output = json_decode($jsonReceiveData);
$task = $json_ouput->text;
$uniquekey = $json_output->unk;
*/
echo $_POST;
/*
$stmt = $pdo->prepare("INSERT INTO todo (id, tekst, uniquekey) VALUES ('', :tekst, :unk)");
$stmt->bindParam(':unk', '1');
$stmt->bindParam(':tekst','testing');
$stmt->execute();
*/

}

SOLUTION:

$data = json_decode(file_get_contents("php://input"), true);
$task = $data['text'];

The object was found in php://input

Biskrem Muhammad
  • 4,074
  • 3
  • 31
  • 38
Laurens Mäkel
  • 815
  • 2
  • 12
  • 29

2 Answers2

17

The user solved it "finding" the object in php://input

$data = json_decode(file_get_contents("php://input"), true);
$task = $data['text'];

As pointed by STEEL, it was an issue at the PHP code, not React or Axios.

Felipe G.
  • 154
  • 1
  • 9
-7

Just need:

if(isset($_POST['text'])) { ... }
Karlova
  • 11
  • 1
  • 3