{}

Submit JSON with HTMX

Use the Submit JSON API to wire up a contact us form submission notification using HTMX

Check out our blog post How to POST JSON Data with HTMX for more details on how to handle JSON requests & responses with HTMX.

ʕ •ᴥ•ʔつ💚


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Submit JSON HTMX Example</title>
  <script src="https://unpkg.com/htmx.org"></script>
</head>

<body>
  <form 
    id="contactForm" 
    hx-target="#response" 
    hx-post="https://api.submitjson.com/v1/submit/xxxxxxxx"
    hx-ext="submitjson"
  >
    <input type="text" name="name" placeholder="Name" required><br>
    <input type="email" name="email" placeholder="Email" required><br>
    <textarea name="message" placeholder="Message" required></textarea><br>
    <button type="submit">Send</button>
  </form>

  <div id="response"></div>

  <script>
    htmx.defineExtension('submitjson', {
      onEvent: function (name, evt) {
        if (name === "htmx:configRequest") {
          evt.detail.headers['Content-Type'] = "application/json"
          evt.detail.headers['X-API-Key'] = 'sjk_xxx'
        }
      },
      encodeParameters: function(xhr, parameters, elt) {
        xhr.overrideMimeType('text/json')
        return (JSON.stringify({ data: parameters }))
      }
    })
  </script>
</body>
</html>
html