Home
| Colors: |

Submit POST Form Data With JavaScript

April 2025

Introduction

I'm working on a personal browser extension1 for my Grimoire2. I need it to send data to the local server that provides the backend3. This is how I'm doing that:

HTML

<button id="submit-button">Submit</button>
<pre id="output">waiting...</pre>

Output

waiting...
JavaScript
async function sendData(data) {
  const postUrl = "https://echo.hoppscotch.io/";
  const bodyData = JSON.stringify({ 
    "key1": "alfa",
    "key2": "bravo",
  });
  try {
    const response = await fetch(
      postUrl, {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: bodyData,
    });
    const result = await response.json();
    showOutput(result);
  } catch (e) {
    console.error(e);
  }
}

function showOutput(data) {
  const outputEl = document.querySelector(
    "#output"
  );
  outputEl.innerHTML = JSON.stringify(
    data, null, 2
  );
}

const sender = document.querySelector(
  "#submit-button"
);

sender.addEventListener(
  "click", sendData
);

Notes

  • The code on this page is live. If you click the Submit button, it'll run. Assuming the service it's connected to is running, you'll see a response update the <pre id="output"> element.
  • The sendData function is attached to the click handler of the #submit-button.
  • When sendData is triggered it sends a POST request to https://echo.hoppscotch.io with the parameters defined in bodyData
  • The JSON response is stringified and output in <pre id="output"> when it's returned. The payload is an echo which shows the original parameters along with some metadata.
end of line

Footnotes

The idea is to add functionality to the browser so I can open a little window on any page and use it to make a bookmark, grab a quote, or collect videos directly into my Grimoire.

Some call it a notes app. I call it a book of magic.

The backend I'm building that will let me add a bunch of automation to my Grimoire.