form.addEventListener('submit', (e) => {
e.preventDefault();
var name = nameInput.value;
var email = emailInput.value;
var amount = amountInput.value;
console.log(name);
let data = {
name : name,
email : email,
amount : amount,
}
fetch('validator.php', {
method : 'POST',
body : JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
return response.text();
}).then(function(text) {
console.log(text);
}).catch(function(error){
console.error(error);
})
});
Manually inputting a name in the PHP file makes it work, so the problem is clearly how the information is being sent. It's not in the HTML because of the console.log, so any ideas?
<?php
// User data to be displayed later
$name = $_POST["name"];
$email = $_POST["email"];
$amount = $_POST["amount"];
// Check for email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Please enter a valid email";
}
// JSON array
$info = array($name,$email,$amount);
json_encode($info);
?>
Up until the console.log, the information is correct, and it prints correctly. However, I'm getting this error on my browser:
Notice: Undefined index: name in C:\laragon\www\validator.php on line 4 Notice: Undefined index: email in C:\laragon\www\validator.php on line 5
Notice: Undefined index: amount in C:\laragon\www\validator.php on line 6 Please enter a valid email
Here's the html of the form I am using:
<form action="validation.php" method="POST" class="text-center" id="form">
<label for="name" class="form-label" style="color: #1D1C52; font-weight: bold;">Name</label>
<div class="mb-4 w-50">
<input
type="name"
id="name"
name="name"
class="form-control input-field"
required
/>
</div>
<label for="email" class="form-label" style="color: #1D1C52; font-weight: bold;">Email</label>
<div class="mb-4 w-50">
<input
type="email"
id="email"
name="email"
class="form-control input-field"
required
/>
</div>
<label for="amount" class="form-label" style="color: #1D1C52; font-weight: bold;">Amount</label>
<div class="mb-4 w-50">
<input
type="number"
id="amount"
name="amount"
class="form-control input-field"
required
/>
</div>
<div class="container text-center">
<div class="row gx-0">
<div class="col-6 ps-5">
<div class="clear-btn text-muted" id="clearButton">Clear fields</div>
</div>
<div class="col-5 pe-5 ps-4">
<button type="submit" class="btn" style="color: white; background-color: #1D1C52;" id="submitButton">Submit</button>
</div>
</div>
</form>