Home
Support Forums

Prevent Netlify Form Redirect After Submit

Hello!

I was wondering if there’s a way to prevent a form redirect after a successful form submission. After completing the form, I would like for the user to stay on the same page and not be redirected to a success page. Can this be done by changing the action attribute? Please see my code below.

<form
    className='contact-form'
    id='contact-form'
    name='Contact Form'
    method='POST'
    data-netlify='true'
    action=''
    onSubmit={handleFormValidation}
  >
    <div className='name'>
      <label htmlFor='name'>Name</label>
      <input
        type='text'
        name='name'
        id='name'
        value={formValues.name}
        onChange={handleFormValues}
      />
      <div>{errorValues.name}</div>
    </div>
    <div className='email'>
      <label htmlFor='email'>Email</label>
      <input
        type='text'
        name='email'
        id='email'
        value={formValues.email}
        onChange={handleEmailValidation}
      />
      <div>{errorValues.email}</div>
    </div>
    <div className='subject'>
      <label htmlFor='subject'>Subject</label>
      <input
        type='text'
        name='subject'
        id='subject'
        value={formValues.subject}
        onChange={handleFormValues}
      />
      <div>{errorValues.subject}</div>
    </div>
    <div className='message'>
      <label htmlFor='message'>Message</label>
      <textarea
        style={{ resize: 'none' }}
        name='message'
        id='message'
        value={formValues.message}
        onChange={handleFormValues}
      ></textarea>
      <div>{errorValues.message}</div>
    </div>
    <button type='submit' name='submit' id='submit'>
      Submit
    </button>
  </form>

Based on your onSubmit handler - im assuming this is react.
You can 100 % dictate the behavior of submit handlers through react.

Netlify lets you use their default post submit page, you can also set your own custom page.
You have the action prop listed with no value - by default netlify will route you to their standard success page.

I would try removing action prop, and handling UX through your onSubmit handler

1 Like

I am finding that i can’t stop the redirect in react. When removing the action attribute it redirects, when I pug empty quotes “” it also redirects. WHen i put a # same.

Only thing I can do is put in a ‘/’ to redirect to my own page, but i want to keep the user on the same scroll distance and not refresh the page back to the top.

Any ideas ?

Hey there, @riekus :wave:

Thanks for writing in to the Forums! It looks like it has been a couple days since you posted this. Are you still encountering issues?

If you are still looking for some guidance, we will need a bit more information to help you with this :slight_smile: Can you please share your Netlify site name as well as the repo where your code is? Thank you.

Hi there,

I’m running into the same issue currently… did you manage to find a solution to stop the page from relocating at all?

Here is the form:

<form name="{{ form.form.formName}}" data-netlify="true" data-netlify-honeypot="bot-field" class="ntlForm flex flex-col gap-y-4 justify-between h-full" action="#">

And my logic to submit it with Fetch for reference:

document.querySelectorAll('.ntlForm').forEach(function (form) {
    form.addEventListener('submit', (event) => {
      event.preventDefault()
      let formData = new FormData(form)
      fetch('/', {
        method: 'POST',
        headers: { "Content-Type": "multipart/form-data" },
        body: new URLSearchParams(formData).toString()
      }).then(() => ntlFormSuccess()).catch((error) =>
        alert(error))
    });
  });

Any help with this would be great :slightly_smiling_face:

event.preventDefault() is the method that you need and i can see that you already have it.

So the only reason why your page would still redirect is because of ntlFormSuccess(). Could you share its source?

Additionally, if you can share the link of the page causing it, that would be great.

Hi @hrishikesh,

Here is the complete logic including ntlFormSuccess():

  document.querySelectorAll('.ntlForm').forEach(function (form) {
    form.addEventListener('submit', (event) => {
      event.preventDefault()
      let formData = new FormData(form)
      fetch('/', {
        method: 'POST',
        headers: { "Content-Type": "multipart/form-data" },
        body: new URLSearchParams(formData).toString()
      }).then(() => ntlFormSuccess()).catch((error) =>
        alert(error))
    });

    function ntlFormSuccess() {
      console.log("form submitted")
      form.reset();
      document.querySelector(".successNoti").style.display = "inline";
    }
  });

And an example case would be Get in touch

Thanks,

I tried to submit the form and I wasn’t redirected anywhere. Are you really seeing this issue?

Yes still seeing this

I just deployed a new build that removed the / in the action attribute. Could you try refreshing?

Update:
On the second submission (after clicking “back to our site” and re-inputting fields) it works as expected. Seems this is only an issue on first load, and even then if you refresh a couple times and try again you still see default Netlify submission alert.

Nope, still not getting any redirect. Could you try a different device/browser?

This is the behaviour I am seeing now

Are you sure your JavaScript is loading fine and the event listener is working?

You can select the form element in dev tools in Chrome and go to Event Listeners tab to see if the listener has been set up correctly.

Yep, still seeing this on other devices and browsers, the site as a service worker, can you please ensure that you have deleted cache and are seeing the most recent commit.

All good even with removing the service worker.

Could you ask someone else to test just to be sure?

Test the event listener?

It appears to be working since on both times the form is submitted it successfully gets sent to Netlify. I’m just not too sure why Netlify’s submission page appears on the first time round… that’s why I assumed it was a Netlify Form related issue.

Netlify Forms doesn’t control your JavaScript. If your JavaScript doesn’t call the event.preventDefault() method in time, the form would be submitted like a normal HTML form and would display the form submission page.

I’m not saying test the event listener, I’m saying ask someone else to test because I can’t reproduce the issue. The code you’ve written is correct, but if the browser is still ignoring preventDefault() for some reason, it would be interesting to see if there’s anyone else seeing this too.

1 Like

Thanks @hrishikesh for the suggestion, I asked someone to test out a submission and they didn’t run into the default page. Do you have an idea to what is causing it to happen only on my machine?

I won’t be able to guess at my first shot as nothing seems obvious.

I’d suggest to check the dev tools to see if the event listener is attached to the form correctly (make sure ancestors is turned off):

If it’s attached and it’s redirecting, that would be a real problem. In this case, you could go to the sources tab and add a breakpoint at each line in your function to see if any of that is failing by any chance.

If it’s not attaching the event listener, something is going wrong while JavaScript is trying to attach event listeners to all the forms in querySelectorAll.

it’s still weird as to why it’s happening only on your device, but well, maybe you’ve got a cached copy yourself?

1 Like