How to Post a Page Without Posting

I love a good paradox. Things like "silent alarm", "virtual reality", and the developer favourite: "posting a page without actually posting it".

Let’s say you’re building a mini web editor — a neat little HTML page with a <textarea> where people can type important things like novel chapters, shopping lists, or which biscuits they have in the cupboard.

The natural instinct is to wrap it in a <form> and let the browser do its thing when the user hits “Send”. Which works… but also reloads the page and clears the form — along with your carefully curated biscuit list.

Enter JavaScript: the Form Whisperer

What you want is a way to grab the form submission event before it fires off into the great unknown. Something like this:

document.getElementById("editorForm").addEventListener("submit", function(event) {
  event.preventDefault(); // Stop the page from reloading

  const text = document.getElementById("editor").value;

  fetch("/save", {
    method: "POST",
    headers: { "Content-Type": "text/plain" },
    body: text
  })
  .then(response => {
    if (!response.ok) throw new Error("Network error");
    return response.text();
  })
  .then(data => {
    console.log("Saved!", data);
  })
  .catch(error => {
    alert("Couldn't save your work: " + error.message);
  });
});

Binding the Save Event

That first line is the key:

document.getElementById("editorForm").addEventListener("submit", function(event) { ... });

It hooks into the form with the ID editorForm and listens for a submit event — i.e., when the user clicks the button. Then it politely stops the browser from doing its reload dance with event.preventDefault() and takes control of the situation.

Meanwhile, the text from the <textarea> with the ID editor is posted using fetch(), but the page doesn’t move an inch. It’s like sending a message by owl: invisible, efficient, and highly magical.

Minimal HTML Example

Here’s the whole thing in one slice:

<form id="editorForm">
  <textarea id="editor">Type your genius here...</textarea><br>
  <button type="submit">Send</button>
</form>

No Page Refresh. No Lost Content. No Panic.

You can even flash up a little error message if something breaks. Because nothing ruins creativity like silent failure. Well, except maybe stale biscuits.

Thanks to ChatGPT for help writing this.