Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
53 lines (46 loc) · 1.87 KB
/
Copy pathscript.js
File metadata and controls
53 lines (46 loc) · 1.87 KB
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
// Formclick form API: one POST request, no backend of your own.
const ENDPOINT = 'https://api.formclick.io/submit';
// Your form's access key from the Formclick dashboard.
// It can only create submissions, so it's safe in client-side code.
const ACCESS_KEY = 'YOUR_ACCESS_KEY';
const form = document.getElementById('contact-form');
const errorEl = document.getElementById('form-error');
const button = form.querySelector('button[type="submit"]');
function showError(text) {
errorEl.textContent = text;
errorEl.hidden = false;
}
form.addEventListener('submit', async (event) => {
event.preventDefault();
errorEl.hidden = true;
if (!ACCESS_KEY || ACCESS_KEY === 'YOUR_ACCESS_KEY') {
showError('Set ACCESS_KEY at the top of script.js to your Formclick access key.');
return;
}
// Every field with a name is sent. _honeypot stays empty for real visitors.
const data = Object.fromEntries(new FormData(form));
button.disabled = true;
button.textContent = 'Sending…';
try {
const res = await fetch(ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ ...data, access_key: ACCESS_KEY, subject: 'New message from the JavaScript contact form' }),
});
const result = await res.json(); // { success, message }
if (res.ok && result.success) {
form.reset();
document.getElementById('form-card').hidden = true;
document.getElementById('thanks-card').hidden = false;
} else if (res.status === 429) {
showError('Too many attempts. Please wait a few minutes and try again.');
} else {
showError(result.message || 'Something went wrong. Please try again.');
}
} catch {
showError('Network error. Please check your connection and try again.');
} finally {
button.disabled = false;
button.textContent = 'Send message';
}
});