Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react.js using axios to post data to php, but php echo empty

I am using react.js, axios, and PHP to post data to MySQL database

This is my react.js code

sendData(){
var data = new FormData();
data.append('name', 'jessie');
data.append('time', '12:00');
data.append('food', 'milk');
data.append('nutrition', 'vitaminA');
axios.post(
'./sendData.php',{
  data: data

})
.then(response => {
console.log(response)
console.log(response.data)
this.filter = response.data
})
.catch(e => {
this.errors.push(e)
})
}

And this is my PHP code

<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$database = "mydb";


$conn = new mysqli($servername, $username, $password, $database);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully yayaya";
echo "the post after this";
echo json_encode($_POST);

?>

And this is my Chrome Console

Connected successfully yayayathe post after this[]

I don't know why my PHP get empty data and echo empty value.

like image 792
Zak Chen Avatar asked Sep 18 '17 08:09

Zak Chen


1 Answers

According to the axios docs

By default, axios serializes JavaScript objects to JSON.

One option is to read json from the body in your PHP code:

$entityBody = file_get_contents('php://input');

Then there's no need to wrap your data in FormData, you can just add it directly:

axios.post(
'./sendData.php',{
  data: {
    name: 'jessie',
    time: '12:00',
    food: 'milk',
    nutrition: 'vitaminA'
  }
})

Another option is to set the Content-type header in axios:

axios.post(
  './sendData.php',{
  data: data
  {
    headers: {
      'Content-type': 'multipart/form-data'
    }
  }
})

Option 1 seems better to me though

like image 65
Austin Greco Avatar answered Sep 26 '22 04:09

Austin Greco