Я отправляю контактную форму в свой бэкэнд-скрипт с формой начальной загрузки и ajax.
return false
не препятствует повторной отправке моей формы после обратного вызова ajax. Это вызывает новую проверку формы начальной загрузки, отображающую сообщения об ошибках ввода.
Я читал некоторые похожие вопросы даже с event.preventDefault()
, но это не сработало.
HTML
<body>
<form id="contact-form" method="POST" class="needs-validation" onsubmit="return false" novalidate>
<div class="form-group">
<label for="name">Nome</label>
<input type="text" name="name" id="name" class="form-control" required />
<div class="invalid-feedback">
Please, type your name
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" required />
<div class="invalid-feedback">
Please, type your e-mail
</div>
</div>
<div class="form-group">
<label for="subject">Assunto</label>
<input type="text" name="subject" id="subject" class="form-control" />
</div>
<div class="form-group">
<label for="message">Mensagem</label>
<textarea name="message" id="message" class="form-control" rows="3" required minlength="10"></textarea>
<div class="invalid-feedback">
Leave your message
</div>
</div>
<button type="submit" class="btn send-btn">Enviar</button>
<div id="messages" class="show_messages"></div>
<div id="error_messages" class="show_error"></div>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script>
(function () {
'use strict';
window.addEventListener('load', function () {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if (form.checkValidity() === true) {
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
var url = "./serverside/send-mail.php";
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function (data) {
console.log(data);
var response = JSON.stringify(data);
console.log(response);
if (data == "\"E-mail sent\"") {
console.log("email sent after stringify");
$("#messages").addClass("messages")
.html("<img src='./img/check.png' alt='Check' /> Message sent!")
.hide().fadeIn(800, function () {
setTimeout(() => {
$("#messages").hide(500);
}, 3000);
});
$('#contact-form')[0].reset();
} else {
$('#contact-form')[0].reset();
console.log("E-mail was not sent");
$("#error_messages").addClass("error_messages")
.html("<img src='./img/warning.png' alt='Warning' /> Ops! Error sending your message.")
.hide().fadeIn(800, function () {
setTimeout(() => {
$("#error_messages").hide(500);
}, 3000);
});
}
},
error: function (e) {
console.log(e);
$("#error_messages").addClass("error_messages")
.html("<img src='./img/warning.png' alt='Warning' /> Ops! Error sending your message.")
.hide().fadeIn(800, function () {
setTimeout(() => {
$("#error_messages").hide(500);
}, 3000);
});
}
});
return false;
}
}, false);
});
}, false);
})();
</script>
</body>