hypothetical/traditional-bootstrap/resources/js/contact.js

68 lines
2.1 KiB
JavaScript
Raw Normal View History

// contact form functionality
2016-01-03 19:08:53 -05:00
function contactFormInit() {
const $form = $("#contact-form"),
$input = $form.find(":input"),
$name = $form.find("[name='name']"),
$email = $form.find("[name='email']"),
$message = $form.find("[name='message']"),
$token = $form.find("[name='_token']"),
$submit = $form.find("[name='submit']"),
$notify = $form.find(".notification");
let contact = {},
2016-01-03 19:08:53 -05:00
submitting = false;
const getContactData = function() {
2016-01-03 19:08:53 -05:00
contact = {
name: $name.val(),
email: $email.val(),
message: $message.val(),
_token: $token.val()
2016-01-03 19:08:53 -05:00
};
};
$submit.on("click", function(e) {
2016-01-03 19:08:53 -05:00
e.preventDefault();
if (!submitting) {
submitting = true;
getContactData();
$.ajax({
type: "POST",
url: "/api/contact-submit",
2016-01-03 19:08:53 -05:00
data: contact
}).always(function(response) {
let errors;
$form.find(".error").removeClass("error");
$notify.removeClass("visible");
2016-01-03 19:08:53 -05:00
if (response === "success") {
$input.attr("disabled", true);
$submit.addClass("disabled");
$notify.text("Thanks for your message!").addClass("success").addClass("visible");
2016-01-03 19:08:53 -05:00
} else {
errors = 0;
2016-01-03 19:08:53 -05:00
// add the error class to fields that haven't been filled correctly
for (let errorName in response.responseJSON.errors) {
if ($form.find(`[name='${errorName}']`).length) {
$form.find(`[name='${errorName}']`).addClass("error");
2016-01-03 19:08:53 -05:00
errors++;
}
}
if (errors > 0) {
$notify.find("span").text(errors);
$notify.addClass("visible");
2016-01-03 19:08:53 -05:00
}
// re-enable submitting
submitting = false;
}
});
}
});
}