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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With