Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

process Axios POST in PHP [duplicate]

Tags:

php

axios

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

like image 357
Laurens Mäkel Avatar asked May 04 '17 21:05

Laurens Mäkel


1 Answers

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.

like image 164
Felipe G. Avatar answered Nov 03 '22 18:11

Felipe G.