Making a newsletter backend
&gt; <i>Some JavaScript on this site that’ll ask the backend to sign up a new user.</i><p>This makes me sad. The browser has perfectly good form submission stuff that doesn’t need JavaScript, and there’s seldom any actual reason to <i>require</i> JavaScript. Yet I find it increasingly common that web developers, despite perhaps (hopefully!) still using &lt;form&gt; and &lt;input type=submit&gt;, are somehow unaware of this and assume JavaScript <i>must</i> be used, and use JSON encoding, and trip up over CORs, and… and… Whereas in fact, you only need JavaScript to support seamless content changes based on the form submission (providing feedback or whatever without loading a new version of the page with just that alteration), and it’s normally perfectly reasonable to support normal form submission with just a slight enhancement if JavaScript runs.<p>Here’s an alteration of the newsletter form, which assumes that &#x2F;subscribe is a regular HTTP form submission endpoint, accepting application&#x2F;x-www-form-urlencoded form data and returning a basic message as an HTML fragment (or even plain text):<p><pre><code>  &lt;div class=&quot;hover-div blog-post-container pastel-depth-4 lift-on-hover&quot; id=&quot;newsletter_signup&quot; style=&quot;border-radius: 14px;&quot;&gt;
  &lt;h3 style=&quot;margin-top: 6px&quot;&gt;Newsletter&lt;&#x2F;h3&gt;
  &lt;form id=&quot;sign_up_for_newsletter_form&quot; method=&quot;post&quot; action=&quot;https:&#x2F;&#x2F;axleos-blog-newsletter.ew.r.appspot.com&#x2F;subscribe&quot; target=&quot;_blank&quot;&gt;
  [… seven unchanged lines omitted for brevity …]
  &lt;&#x2F;form&gt;
  &lt;script&gt;
      sign_up_for_newsletter_form.addEventListener(&quot;submit&quot;, async function(event) {
          event.preventDefault();
          let response = await fetch(this.action, {
              method: &quot;POST&quot;,
              body: new URLSearchParams(new FormData(this)),
          });
          newsletter_signup.innerHTML =
              response.ok
                  ? &quot;&lt;p&gt;Signup successful!&lt;&#x2F;p&gt;&quot;
                  : `&lt;p&gt;Signup failed: ${response.statusText} &#x2F; ${await response.text()}&lt;p&gt;`;
      });
  &lt;&#x2F;script&gt;
</code></pre>
A few notes:<p>• I’ve added the method, action and target attributes to the &lt;form&gt; element. The consequence of this is that regular form submission, if the JavaScript isn’t run for whatever reason, will submit the data to that URL in a new window, the idea being that the user just gets a new page containing “signup successful” and nothing else. (By contrast, on the current page, submitting the form will submit to the current URL with ?email=… added, appearing to the user as though the page has just reloaded, and it won’t be clear whether or not it worked.)<p>• I’ve shifted the &lt;script&gt; element from before the form to after it, so that the form exists when the script is run, so that it can do its thing immediately rather than being deferred until the page finishes loading by wrapping it in $(document).ready(function(){…}) (or addEventListener(&quot;DOMContentLoaded&quot;, function(){…}) would be non-jQuery equivalent, so long as it’s still an inline script). This is very desirable if the scripts are inline anyway, and quantities like this should basically always be inline for the best performance (seriously, inlining all your JS and CSS yields the best performance until surprisingly large sizes—far past 100 KB in practically all deployment and access scenarios, <i>even with a warm cache</i>). You only want ready dances if you’re deliberately loading the script asynchronously (which I will also defend as not unreasonable for something like this: the document is fully interactive without it, it can run later or even not at all and cause no problem).<p>• I’ve removed jQuery usage because it’s simply not necessary ($(&quot;#…&quot;) → document.getElementById(&quot;…&quot;), .on() → .addEventListener(), $.ajax() → fetch()); all the native alternatives have excellent browser support. I’ve also used native async&#x2F;await because it makes things a tad nicer. (It’s not a compatibility hazard, because ancient browsers will just call it a syntax error and not execute the script, and thus get the no-JS regular form submission behaviour.)<p>• I dislike this use of innerHTML with the response text; a little too fragile if you try sending plain text but it ends up including HTML syntax, or if you can get things like unexpected server error HTML from Google App Engine or gunicorn or whatever and now you’re dropping a whole &lt;html&gt;…&lt;&#x2F;html&gt; in there with unknown contents. But I’m matching the original.<p>• I’ve written just sign_up_for_newsletter_form and newsletter_signup with no document.getElementById(&quot;…&quot;) wrapping just for the fun of it, showing off my favourite HTML+JavaScript golfing technique. It’s a matter of very ancient history, but part of the spec &lt;<a href="https:&#x2F;&#x2F;html.spec.whatwg.org&#x2F;multipage&#x2F;nav-history-apis.html#named-access-on-the-window-object" rel="nofollow noreferrer">https:&#x2F;&#x2F;html.spec.whatwg.org&#x2F;multipage&#x2F;nav-history-apis.html...</a>&gt; and it works everywhere. Decide for yourself whether it’s wise. (Personally I think the concerns about it <i>in cases like these</i> are somewhat overblown, but at the very least it’s certainly a technique that should not be scaled.)<p>• The `new URLSearchParams(…)` wrapping is to get application&#x2F;x-www-form-urlencoded, for consistency with normal form submission. Just `body: new FormData(this)` uses multipart&#x2F;form-data encoding, which regular form submission will only use if you’re uploading files via &lt;input type=&quot;file&quot;&gt;. A little janky, in my opinion, being different from normal form submission, even if simply splitting on type makes a deal of sense. Anyway, all serious HTTP server libraries will support both encodings of form data, so you aren’t likely to <i>need</i> it, but I figured I’d make it consistent anyway, because otherwise experience says mistakes get made. The goal is to minimise the differences between the no-JS and JS pathways, to minimise the chances of the no-JS way accidentally breaking.<p>• I replaced the button click handler with a form submit handler. Personal preference, to a considerable extent, with no actual practical difference since the button is an &lt;input type=&quot;submit&quot;&gt;. (Pressing Enter from the email field will trigger clicking on the first submit button: &lt;<a href="https:&#x2F;&#x2F;html.spec.whatwg.org&#x2F;multipage&#x2F;form-control-infrastructure.html#implicit-submission" rel="nofollow noreferrer">https:&#x2F;&#x2F;html.spec.whatwg.org&#x2F;multipage&#x2F;form-control-infrastr...</a>&gt;.)<p>• I hold out hope that <i>eventually</i> we might get some kind of auto-resizing iframe (one starting point on the topic: &lt;<a href="https:&#x2F;&#x2F;github.com&#x2F;whatwg&#x2F;html&#x2F;issues&#x2F;555">https:&#x2F;&#x2F;github.com&#x2F;whatwg&#x2F;html&#x2F;issues&#x2F;555</a>&gt;), so that you could put a response iframe below the form and make it the target. This exposes another approach: put the form inside an iframe, and then just use normal submission entirely. The only problem (and it’s not a tiny problem, unfortunately) is this matter of sizing the iframe.<p>—⁂—<p>I would also suggest adding a simple honeypot field to the form: <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=37058847">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=37058847</a>