Static form with ajax submited, but successful window doesn't show

Hello. I need a help. I have a static form and it’s very simple.
Without js it works perfectly, but I have attached js-file with simple validation for second field and fetch and I don’t get successful page (by netlify).

I tried many solutions, but it doesn’t work. After submit I get values from form at my netlify service, and also I get a 200 ok response for fetch (at Network page in Tools), but I don’t get successfull message netlify page. Nothing happends with page…

I tried to fix it in many different ways - I added and removed action, changed attribute data-netlify=“true” for netlify, I tried to add hidden input… It didn’t help. I will be gratefull for any solution.

My code is below:

<form
      class="contact-form js-form"
      name="contact-form"
      method="POST"
      data-netlify="true"
      action="thank-you"
    >
      <input
        class="contact-form__input contact-form__input-name"
        name="username"
        id="username"
        type="text"
        placeholder=" "
        aria-label="input for your name"
      />

      <input
        class="contact-form__input contact-form__input-email js-form-input-email"
        type="email"
        id="email"
        name="email"
        placeholder=" "
        title="Email address must contains symbols '@' and '.'"
        aria-label="input for your email"
      />

      <button
        class="contact__submit-button button-accent"
        type="submit"
        name="submit"
      >
        Send
      </button>
    </form>

and js-file:

const formRef = document.querySelector(".js-form");

const requiredFormInputRef = document.querySelector(".js-form-input-email");

formRef.addEventListener("submit", onFormSubmit);

function onFormSubmit(event) {
  event.preventDefault();
  const userEmail = event?.currentTarget?.elements?.email?.value;

  if (
    userEmail.trim() === "" ||
    !userEmail.includes("@") ||
    !userEmail.includes(".")
  ) {
    requiredFormInputRef.focus();
    requiredFormInputRef.classList.add("invalid");

    const removeClassTimeout = setTimeout(() => {
      requiredFormInputRef.classList.remove("invalid");

      clearTimeout(removeClassTimeout);
    }, 5000);
  } else {
    if (requiredFormInputRef.classList.contains("invalid")) {
      requiredFormInputRef.classList.remove("invalid");
    }

    const formData = new FormData(formRef);

    fetch("/", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams(formData).toString(),
    })
      .then(() => {
        console.log("Form successfully submitted");

        formRef.reset();
      })
      .catch((error) => console.log("Sending form failed"));
  }
}

network
data at server

Hi @nadiia

Because the form is submitted using AJAX, no redirect to a success page will occur. The only thing that will happen (as per the code above) is Form successfully submitted is logged to the console and the form is reset.

If you want to redirect a user to a success page, or show a success message on the current page, you will need to add the code to handle that in place of the console.log.

Hi @coelmay . Thanks for your reply.

Can I add the code, which will redirect user to a success page, that is provided by netlify?
I really want to do this. If it is possible, please, write me the code you talking about.

P.S. If I remove code with fetch success page still not shown.

You can’t redirect to the built-in Netlify success page. But you could redirect to your own.

Something as simple as adding

window.location = "/success"

might well suit your needs (assuming your success page was success.html.)

However, keeping someone on the same page as the form and showing a success message even as simple as

alert("Your message was sent.")

is potentially more preferable.

You could show a modal like in this example with a success message, and even if there is an error submitting the form.

I also note the validation code here:

This is not required as you have specified the input type is email, so the browser does the validation. Even so, the code is flawed as it would permit m.@ as a valid email address (which it isn’t.) If you still want to validate the email address, have a read over this question on Stack Overflow which outlines several methods

Thank you so much! I can redirect to my own page. Thank you for your reply about my validation. I added it because I have to show custom notification above the form.

But I think, there have to be a way to show successful window provided by netlify. It seems to me that I saw it, but I don’t understand, why it doesn’t work in my simple code :pensive:

If you want to show the success page provided by Netlify, then don’t use the AJAX submit method.

The idea of using the AJAX method is it give you control over the action post submission (as mentioned previously with modals, and redirects.)

Do you mean that I can use my js function, but remove fetch? Because I tried this and it’s not working. My page stop be shown after I add js. No matter what is inside the function…

I’vw just tried to comment all code inside my function beside evt.preventDefault(), and it’s not working, and I do’nt get any form data at my server. How can I add my js-function (for custom validation) but also get success netlify page?

What the URL for the page?

https://dulcet-mooncake-9f4fd9.netlify.app/

By leaving the event.preventDefault() in the onFormSubmit() function, you are stopping the form from submitting. As mentioned in Event.preventDefault() - Web APIs | MDN

The preventDefault() method … default action should not be taken as it normally would be.

Thank you so much!

It’s solution - I moved event.preventDefault() inside of the condition when value is not valid.

And now - I get a result what I need - if field value is valid, I get a successfull page, and if it is not - I reset page reload and get my custom notification.

Thank you very much. I am so glad and grateful :star_struck:

1 Like