Prevent data from being resent after reload - Contact form

hello,
i use the contact form like in the cookbook Email contact form | Kirby CMS.

If the user reloads the page or comes back to the page, the data will be sent again.

If I don’t send the user after the successful send to another page - what can I do to prevent the data from being sent again? How to unset $data after send.

controller - Works without resending

// no exception occurred, let's send a success message
if (empty($alert) === true) {
go(some page');
}

controller - resends data

// no exception occurred, let's send a success message
if (empty($alert) === true) {
$success = 'Your message has been sent, thank you. We will get back to you soon!';
$data = [];
}

Thank you!

The standard way of handling this is via the so called post-redirect-get pattern, i.e. you redirect after successful execution.

hi there.
iam currently implementing a contact form as well with the help of your cookbook example.
the mentioned pattern would not work in that example right?. because it would not return any data. is this correct? but where to implement the pattern and how should the controller look like then? can you point my in the right direction since its a long time ago i did such things in php and not in the frontend via js? (want to stick with php and “regular” post in this case).
thanx in advanced.

regards bob

You can find a redirect example in one of the other recipes: Email with attachments | Kirby CMS

Data is stored in the session in this example, so that it can be printed on the success page.

setting the disabled prop on the submit button after the submit event fired can also prevent duplicate submissions. but be wary you might need a way to unlock it again if the form does not validate.

something like this for ajax posting a form

 <script>
          const form = document.querySelector('form.myform');
          form.addEventListener('submit', async function (event) {
            event.preventDefault();
            const btn = document.querySelector('button.form-submit');
            btn.disabled = true;
            setTimeout(() => btn.disabled = false, 2000)
            const formData = new FormData(form);
            try {
              const response = await fetch(form.action, {
                method: 'POST',
                body: formData,
              });
              if (response.ok) {
                 // do stuff
              } else {
                // do stuff
              }
            } catch (error) { console.log(error); }
          });
        </script>

thanx for your replies.
ill go with session variables in this case. it fits better to my usecase in my current project.

regards bob