问题
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");
}
}
?>
回答1:
Preventing the default on the submit button should theoretically stop form submission—but:
- there is no
submit
event for an input button. If you listen toclick
, that will work, but only partially because... - there might be other confounding factors that is interfering with this, i.e. other keystrokes or user interactions that causes the form to be submitted.
You should be listening to the onsubmit
event fired from the form, instead of the event emitted from the submit button. The form's submit event is the definite event that is fired when a form is submitted: be it triggered by <button>
, <input type="submit">
, or even programatically, such as $form.trigger('submit')
. You can give your form an ID, i.e.:
<form method="post" name="registerForm" class="form" id="registrationForm">
And then simply perform the exact same logic in the onsubmit
callback:
$('#registrationForm').on('submit', function(e) {
// Prevent form submission by the browser
e.preventDefault();
// Rest of the logic
});
If you can't modify the DOM such that you can identify the <form>
element, using jQuery's DOM traversal methods will also work, i.e.:
var $form = submitButton.closest('form');
$form.on('submit', function(e) {
// Prevent form submission by the browser
e.preventDefault();
// Rest of the logic
});
To illustrate my statement that the form's submit event serves as an "umbrella" that captures all submission events, regardless of how they are triggered, refer to the example I have attached below:
$(function() {
$('#form').on('submit', function(e) {
console.log('Form submission captured. It is triggered by: ', document.activeElement);
//e.preventDefault();
});
$('#submitInput').on('submit', function(e) {
console.log('Triggering submit event from <input>');
});
$('#submitButton').on('click', function() {
console.log('Triggering submit event from <button type="submit" />');
});
$('#submitProgramatically').on('click', function() {
console.log('Triggering submit event using JS only');
$('#form').trigger('submit');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#">
<input type="text" placeholder="Just another text field" />
<br />
<input type="submit" value="Submit using an <input>" id="submitInput" />
<br />
<button id="submitButton">Submit using a <button></button>
<br />
<a href="#" id="submitProgramatically">Submit programatically using JS</a>
</form>
Note: You can bypass jQuery's onsubmit
event handler if you call the submit()
method directly on the DOM node: $('form')[0].submit()
.
来源:https://stackoverflow.com/questions/45735757/stop-page-refresh-after-form-submit