forked from raspgot/Contact-Form-PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AjaxForm.js
89 lines (85 loc) · 2.89 KB
/
AjaxForm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// .validate (https://jqueryvalidation.org)
// .post (https://api.jquery.com/jQuery.post/)
// reCaptcha v3 (https://developers.google.com/recaptcha/docs/v3)
// @author Raspgot
const publicKey = ""; // GOOGLE public key
// Get token from API
function check_grecaptcha() {
grecaptcha.ready(function () {
grecaptcha.execute(publicKey, {
action: "ajaxForm"
}).then(function (token) {
$("[name='recaptcha-token']").val(token);
});
});
}
// Show response in .toast
function toastShowing(response) {
$(".toast-body").html(JSON.parse(response));
$(".toast").toast('show');
}
$(function () {
check_grecaptcha();
$("#contactform").validate({
// Form fields rules
rules: {
name: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 5
}
},
// Error messages
messages: {
name: {
required: "Please enter your name.",
minlength: "Must be at least 3 characters long."
},
email: "Please enter a valid email.",
message: {
required: "Please enter your message.",
minlength: "Must be at least 5 characters long."
}
},
errorClass: "invalid-feedback",
// Dynamic validation classes
highlight: function (element) {
$(element).addClass("is-invalid").removeClass("is-valid");
},
unhighlight: function (element) {
$(element).addClass("is-valid").removeClass("is-invalid");
},
// Action on submit
submitHandler: function (form) {
$(".spinner-border").removeClass("d-none");
$("#sendtext").addClass("d-none");
$.post(form.action, $(form).serialize())
.done(function (response) {
toastShowing((response));
$(".spinner-border").addClass("d-none");
$("#sendtext").removeClass("d-none");
$("#submit-btn").prop("disabled", true);
check_grecaptcha();
setTimeout(function () {
$("#submit-btn").prop("disabled", false);
$("form").trigger("reset");
$("form").each(function () {
$(this).find(".form-control").removeClass("is-valid")
})
}, 3000);
})
.fail(function (response) {
toastShowing((response));
$(".spinner-border").addClass("d-none");
$("#sendtext").removeClass("d-none");
});
}
});
});