Skip to main content

max / makenotwork

1.6 KB · 38 lines History Blame Raw
1 // Landing "notify me", the enhanced path. The form posts to /notify on its
2 // own with JS off; this submits the same route and the same encoding over
3 // fetch so the visitor keeps their place on the page instead of reloading it.
4 // Posting the form verbatim also means the CSRF token rides along without
5 // being read out and re-attached by hand.
6 function submitNotify(e) {
7 e.preventDefault();
8 var form = document.getElementById('notify-form');
9 var status = document.getElementById('notify-status');
10 var btn = form.querySelector('button');
11 btn.disabled = true;
12 btn.textContent = 'Sending...';
13 status.textContent = '';
14 status.className = 'notify-status';
15 fetch(form.action, {
16 method: 'POST',
17 headers: {'Accept': 'application/json'},
18 body: new URLSearchParams(new FormData(form))
19 }).then(function(r) {
20 // The route answers a redirect to /?notify=ok or /?notify=invalid.
21 // fetch follows it, so the landed URL is what says which happened.
22 if (!r.ok) throw new Error('Something went wrong');
23 if (r.url.indexOf('notify=invalid') !== -1) {
24 throw new Error('That address didn\'t look right.');
25 }
26 status.textContent = 'You\'re on the list.';
27 status.className = 'notify-status success';
28 form.querySelector('input[name="email"]').value = '';
29 }).catch(function(err) {
30 status.textContent = err.message;
31 status.className = 'notify-status error';
32 }).finally(function() {
33 btn.disabled = false;
34 btn.textContent = 'Notify Me';
35 });
36 return false;
37 }
38