-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajaxForm.js
78 lines (52 loc) · 1.77 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
window.addEventListener("load", init, false);
function init() {
$ = function(arg) {return document.getElementById(arg);}
// vars
var name, lastname, txt, resDiv, cptDiv, statusDiv;
// form data inputs
name = $("name");
lastname = $("lastname");
txt = $("txt");
resDiv = $("res"); // response data
cptDiv = $("cpt"); // google captcha in div
statusDiv = $("status");
// ajax
function sendData(formData) {
var r = new XMLHttpRequest();
r.addEventListener("loadstart",function(e) {statusDiv.innerHTML = "Send data...";}, false);
r.addEventListener("progress",function(e) {statusDiv.innerHTML = "Send data...";}, false);
r.addEventListener("load",function(e) {
statusDiv.innerHTML = "data is sent";
if(e.target.responseText != "fail") {
resDiv.innerHTML = e.target.responseText;
cptDiv.style = "border: none";
grecaptcha.reset();
} else cptDiv.style = "border: 2px solid red";
}, false);
r.open("POST", "post.php");
r.send(formData);
}
// form submit
$("form").addEventListener("submit", function(e) {
resDiv.innerHTML = "";
// check
if(name.value && lastname.value && txt.value) {
// form data
var formData = new FormData();
formData.append("name", encodeURIComponent(name.value));
formData.append("lastname", encodeURIComponent(lastname.value));
formData.append("txt", encodeURIComponent(txt.value));
formData.append("g-recaptcha-response", grecaptcha.getResponse());
// google check & sending
if(grecaptcha.getResponse()) {
cptDiv.style = "border: none";
sendData(formData);
} else {
cptDiv.style = "border: 2px solid red";
}
} else alert("Fields are empty!");
// sending ajax
e.preventDefault();
return false;
}, false);
}