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.
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.
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>
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>
🤩✨ Nice job, you successfully integrated Submit JSON with Astro.