I have searched many other threads about this and I can't see what I am doing wrong, I am trying to send form values to a php file to send as an email, however the pages always refreshes. I have tried using event.preventDefault and return false both before and after my ajax call but none seem to work. What am I missing here here is my code.
HTML
<form method="post" name="registerForm" class="form">
<label for="fullName" class="form__fullname form__label">Full Name</label>
<input type="text" name="fullName" placeholder="Richard Thomson" maxlength="40" tabindex="1" pattern="^[a-zA-Z\s]*$" class="form__input" id="name" required>
<label for="email" class="form__email form__label">Email</label>
<input type="email" name="email" placeholder="richard.thomson45@gmail.com" tabindex="2" class="form__input" id="email" required>
<label for="telephone" class="form__tel form__label">Phone</label>
<input type="tel" name="telephone" placeholder="07915834998" tabindex="3" pattern="[0-9]{11}" maxlength="11" class="form__input" id="telephone" required>
<input type="submit" value="Submit" name="submit" class="form__submit" id="submit">
</form>
JS
var fullName,
telephone,
email,
submitButton = $("#submit"),
formData;
submitButton.submit(function (event) {
// event.preventDefault();
fullName = $("#name").val();
telephone = $("#telephone").val();
email = $("#email").val();
formData = {
'name': fullName,
'email': email,
'telephone': telephone
};
$.ajax({
type: 'POST',
url: 'email.php',
data: formData,
dataType: 'json'
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log("not working");
});
return false;
});
PHP
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['telephone'])) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = $_POST['email'];
}
if (preg_match("/^[a-zA-Z\s]*$/", $_POST['fullName'])) {
$fullName = $_POST['fullName'];
}
if (preg_match("/[0-9]{11}/", $_POST['telephone'])) {
$telephone = $_POST['telephone'];
}
$telephone = substr_replace(substr_replace($telephone," ",3,0)," ",8,0);
$emailTo = "test@hotmail.co.uk";
$emailFrom = "contact@test.co.uk";
$subject = "I would like to know more about test";
$message = "Name:" . " " . $fullName . "\r\n\r\n";
$message .= "Email:" . " " . $email . "\r\n\r\n";
$message .= "Telephone:" . " " . $telephone;
$headers = "From: $emailFrom \r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
$headers .= "Reply-To: $email \r\n";
$success = mail($emailTo, $subject, $message, $headers);
} else {
echo("Please fill all necessary fields");
}
}
?>