#use button to post data

3 messages · Page 1 of 1 (latest)

tardy shadow
#

<form method="POST">
<input type="text" name="filter" value="SE" hidden />
<a href="w-full h-full" class="group-hover:text-white"> SE </a>
</form>

this is judges.astro.
is it possible if i press the button to post to judges/SE and i handle the post request in the frontmatter whereby i see what slug but in the same page in judges.astro

hidden mangoBOT
#

Hi @tardy shadow. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, it is possible to handle form submissions in Astro using the POST method. However, the code you provided seems to be missing a submit button for the form. You can add a button inside your form like this:

<form method="POST">
  <input type="text" name="filter" value="SE" hidden />
  <button type="submit">Submit</button>
</form>

In your Astro page, you can check for the POST method in the frontmatter and access the form data using Astro.request.formData(). Here is an example from the Astro documentation (https://docs.astro.build/en/recipes/build-forms#recipe):

---
if (Astro.request.method === "POST") {
  try {
    const data = await Astro.request.formData();
    const filter = data.get("filter");
    // Do something with the data
  } catch (error) {
    if (error instanceof Error) {
      console.error(error.message);
    }
  }
}
---

This code checks if the request method is POST, and if so, it tries to get the form data. If the POST request wasn’t sent by a form and the formData is invalid, it catches the error and logs it.

However, please note that this will not redirect you to a new page (judges/SE). If you want to navigate to a new page upon form submission, you might need to handle that on the client-side with JavaScript, or set the action attribute of the form to the desired URL. Astro is designed to minimize JavaScript usage and optimize loading times, so depending on your use case, you might want to consider a different approach.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: