JSFiddle - React, Tailwind, and code Playground

by Michel Plungjan

HTML

<form id="myForm" action="https://httpbin.org/post" method="POST" target="iframe1">
  <input type="text" name="field1" value="" placeholder="Type something and hit enter" />
  <input type="submit" name="anyNameBUTSubmit" value="Optional Submit button" />
</form>

<iframe name="iframe1" id="iframe1" src="about:blank"></iframe>

JavaScript

window.addEventListener("DOMContentLoaded", () => { // when page is loaded
  const form = document.getElementById("myForm");
  form.addEventListener("submit", (e) => {
    e.preventDefault(); // stop submission
    const tgt = e.target; // the form
    console.log(tgt.action)
    fetch(tgt.action, // the URL
        {
          "method": tgt.method,
          body: new FormData(tgt) // the content of the form
        }
      )
      .then(response => response.text()) // return the text
      .then(text => {
        try {
          const targetFrameDocument = document.getElementById(tgt.target).contentWindow.document;
          targetFrameDocument.write(`<pre>${text}</pre>`);
          targetFrameDocument.close();
        } catch (err) {
          const msg = err.message;
          console.log(msg.includes("cross-origin") ? "Sorry this site does not support iframe writing, see the fiddle https://jsfiddle.net/mplungjan/0aj6dmwk/ instead" : msg);
          console.log(text);
        }
      });
  });
});