How to show success message after submitting HTML forms with AJAX?

Hi! I’m trying to show a success/error message after submitting HTML forms with AJAX.

But something is wrong with my code…

HTML

<form
id="contact-form" 
name="contact" 
method="POST" 
data-netlify="true"
data-netlify-recaptcha="true">

*(some form fields...)*

<div class="submit-success" data-submit=""><p>Message sent!🎉</p></div>
<div class="submit-error" data-submit=""><p>Error.</p></div>
</form>

CSS

.submit-success {
    display: none;
}

.submit-success[data-submit="success"] {
    display: block;
}

.submit-error {
    display: none;
}

.submit-error[data-submit="error"] {
    display: block;
}

Javascript:

document
  .querySelector("form")
  .addEventListener("submit", handleSubmit);

const submitSuccess = document.querySelector('.submit-success')
const submitError = document.querySelector('.submit-error')

const handleSubmit = (e) => {
  e.preventDefault();
  let myForm = document.getElementById("contact-form");
  let formData = new FormData(myForm);
  fetch("/", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams(formData).toString(),
  })
    
    .then(() => { submitSuccess.setAttribute('data-submit', success); })
    .catch((error) => { submitError.setAttribute('data-submit', error) });
};

What’s wrong here?:face_with_monocle:

Thanks🙏🏻

hi there, did you see these guides already?

Yes, but i did not find a solution… My JS skills are very basic, so i don’t know how to fix this.

Try this:

HTML:

<form
id="contact-form" 
name="contact" 
method="POST" 
data-netlify="true"
data-netlify-recaptcha="true">

*(some form fields...)*

<div class="submit-success"><p>Message sent!🎉</p></div>
<div class="submit-error"><p>Error.</p></div>
</form>

CSS:

.submit-success, .submit-error {
    display: none;
}

JS:

document
  .querySelector("form")
  .addEventListener("submit", handleSubmit);

const submitSuccess = document.querySelector('.submit-success')
const submitError = document.querySelector('.submit-error')

const handleSubmit = (e) => {
  e.preventDefault();
  let myForm = document.getElementById("contact-form");
  let formData = new FormData(myForm);
  fetch("/", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams(formData).toString(),
  })
    
    .then(() => { submitSuccess.style.display = 'block'; submitError.style.display = null; })
    .catch((error) => { submitError.style.display = 'block'; submitSuccess.style.display = null; });
};

Note, I’ve not checked the rest of your code, just fixed what you asked for. Let us know if you still need help.