Amine
Amine
CDCloudflare Developers
Created by Amine on 1/13/2024 in #pages-help
[Astro SSG] Why i am redirected after a form submit
I think i have fixed my problem, thanks @Befus I thought that it's a problem with my worker /functions/api/submit.js but it was not, it's an Astro problem. Because i was using SSG, if i was using SSR i probably didn't got this redirect.
In SSR mode, Astro pages can both display and handle forms. In this recipe, you’ll use a standard HTML form to submit data to the server. Your frontmatter script will handle the data on the server, sending no JavaScript to the client.
In SSR mode, Astro pages can both display and handle forms. In this recipe, you’ll use a standard HTML form to submit data to the server. Your frontmatter script will handle the data on the server, sending no JavaScript to the client.
Source: Astro doc But i don't want use SSR just for a contact/newsletter form. I think it's possible to do that with SSG, i didn't change anything in functions/api/submit.js file but i did some modifications on my form pages/contact.astro It's look like that:
---
import Layout from '../layouts/Layout.astro';
---

<Layout title='Contact'>
<form id="contact">
<input type="text" name="name" pattern="[A-Za-z]+" required />
<input type="email" name="email" required />
<button type="submit">Submit</button>
</form>
</Layout>

<script is:inline>
const pushForm = async (event) => {
event.preventDefault()
try {
const data = new FormData(event.target);

fetch(`/api/submit`, {
body: data, method: 'post'
})
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
}
}
}
document.getElementById("contact").addEventListener("submit", pushForm);
</script>
---
import Layout from '../layouts/Layout.astro';
---

<Layout title='Contact'>
<form id="contact">
<input type="text" name="name" pattern="[A-Za-z]+" required />
<input type="email" name="email" required />
<button type="submit">Submit</button>
</form>
</Layout>

<script is:inline>
const pushForm = async (event) => {
event.preventDefault()
try {
const data = new FormData(event.target);

fetch(`/api/submit`, {
body: data, method: 'post'
})
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
}
}
}
document.getElementById("contact").addEventListener("submit", pushForm);
</script>
I don't have redirection or page refresh with this code but i don't know if it's the right way to do it or not
4 replies
CDCloudflare Developers
Created by Amine on 1/13/2024 in #pages-help
[Astro SSG] Why i am redirected after a form submit
It's work like the exemple her: https://github.com/cloudflare/submit.pages.dev Form page You have the same redirection when you submit the form. I didn't find how to make my function working without this redirect
4 replies