{}

Submit JSON with Astro

You are most likely using Astro alongside a framework, but for this example the Astro component will be pure HTML.

If you are using a framework, refer to the related examples: Vue Example, Svelte Example, React Example.


1. Initialize an Astro project

To get started, make sure you have a working Astro project. If yo do not, run npm init astro in your terminal and follow the prompts to get up and running.

2. Create a Contact Form Component

Next create a ContactForm.astro component, making sure to import the Submit JSON client inside <script type="module"> from a CDN like unpkg:

https://unpkg.com/submitjson/dist/index.js

<form id="contactForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <label for="message">Message:</label>
  <textarea id="message" name="message" required></textarea>

  <button type="submit">Send Message</button>
</form>

<script type="module">
  import SubmitJSON from 'https://unpkg.com/submitjson/dist/index.js'

  const sj = new SubmitJSON({ apiKey: 'sjk_xxx', endpoint: 'XxXx' })

  document.getElementById('myForm').addEventListener('submit', async function (e) {
    e.preventDefault();

    try {
      const formData = new FormData(this);
      const submission = await sj.submit(formData)
      console.log('Submitted data:', submission)
    } catch (error) {
      console.error('There was a problem with the fetch operation:', error);
    }
  });
</script>
components/ContactForm.astro

3. Include the component in a page

Finally, include the ContactForm in any of your Astro pages.

---
import ContactForm from '../components/ContactForm.astro';
---

<html>
  <head>
    <title>Contact Us</title>
  </head>
  <body>
    <h1>Contact Us</h1>
    <ContactForm />
  </body>
</html>
src/pages/index.astro

🤩✨ Nice job, you successfully integrated Submit JSON with Astro.