When submitting a contact form, I want to display and hide a spinner on the submit button. The spinner should be visible while the form is being submitted and hidden once the submission is complete.
Below is the code for my submit button with the spinner:
<div class="d-flex justify-content-center">
<button class="btn btn-medium btn-fancy btn-primary mb-0 ls-wider" type="submit" id="submitButton">
<span class="submitSpinner spinner-border spinner-border-sm me-1"></span> Send Message
</button>
</div>
Additionally, here is the AJAX function that handles the form submission:
$(document).ready(function() {
$('.submitSpinner').css('display','none');
$("#contact-form").submit(function(e) {
e.preventDefault();
$('#submitButton').text('Sending Message');
$('.submitSpinner').css('display','inline-block');
var data = {
'name': $('#name').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'company': $('#company').val(),
'message': $('#message').val(),
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/contact/message/send",
data: data,
dataType: "json",
success: function(response) {
if (response.status == 400) {
$.each(response.errors, function(key, error) {
$('#contact-alerts').append('<div class="col-12 col-md-9 col-lg-7 alert alert-danger alert-dismissible fade in show" role="alert"><button type="button" class="btn-close line-height-unset" data-bs-dismiss="alert" aria-label="Close" ></button>' + error + '</div>')
});
$('.submitSpinner').css('display','none');
} else {
$("#contact-form")[0].reset();
$('#submitButton').text('Send Message');
$('.submitSpinner').css('display','none');
$.magnificPopup.open({
showCloseBtn: true,
items: {
src: '#contact-success'
},
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
midClick: true,
removalDelay: 300,
blackbg: true,
mainClass: 'my-mfp-slide-bottom',
});
}
}
});
});
});