I'm submiting a contact form to my backend script with bootstrap form and ajax.
return false
is not preventing my form from submiting again after ajax callback. This causes a new bootstrap form validation, displaying input errors messages.
I read some similar questions even with event.preventDefault()
but it did not work.
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>
After some tests I finally found the solution. After reset()
the form I should remove the class was-validated
.
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();
form.classList.remove('was-validated');
} else {
...
Maybe it is a workaround but it worked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.