Currently using React for frontend, php for backend with XAMPP/Apache. When I send a POST using the fetch API, It creates two rows in my table, one empty and one with the correct details. I have verified that the js function only runs once (strict mode not the problem), and verified that the php code runs twice. I am fairly new to php and fetch and am at a loss as to why this is happening.
First row is made incorrectly on first run, not sure how. Second is correct.
register.php:
<?php
require_once('cors.php');
require_once('db_connection.php');
$data = json_decode(file_get_contents('php://input'), true);
$username = $data['username'];
$email = $data['email'];
$password = $data['password'];
$street = $data['street'];
$state = $data['state'];
$country = $data['country'];
$fname = $data['fname'];
$lname = $data['lname'];
$phone_number = $data['phone'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
error_log(print_r($country, TRUE)); // prints twice
$sql = "INSERT INTO User (Email, `Password`, Street, `State`, Country, `First Name`, `Last Name`, `Phone Number`, Username)
VALUES ('$email', '$hashed_password', '$street', '$state', '$country', '$fname', '$lname', '$phone_number', '$username')";
$result = $conn->query($sql);
if ($result === TRUE) {
echo json_encode(array("success" => "Account Created Successfully"));
} else {
echo json_encode(array("error" => "There was an error in your submission"));
}
$conn->close();
?>
register.jsx excerpt
const onSubmit = e => {
e.preventDefault() // only prints once
console.log('hello')
if (password === rePassword) {
fetch('http://localhost/teashop/php/register.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(data => {
if ('success' in data) {
setDisplay('login');
}
})
.catch(error => {
console.error('Error fetching products:', error);
}
);