Netlify forms - AJAX not working

I’m trying to set up a Netlify form to send messages from my site.
The form is working (messages are correctly submitted), but I can’t get the AJAX part to work.

On submit, I don’t want the user to be redirected to a thank you page. I want to display a Bootstrap alert with a success/error message under the form.

I have followed the official guidelines but I can’t remove the redirection. No matter what I do I keep on being redirected to Netlify’s default thank you page.

I have searched the forum already but haven’t found a solution for my case. Most user cases are for React. My project is based on Bootstrap, Eleventy and webpack.

Here’s my code.

JS: Netlify forms doropesch js -

HTML: Netlify forms doropesch html -

Live site: Contatti

I’m not a JS expert so I can’t spot the issue…
Can someone help?
Thank you.

Hello @raffaellarinaldi , thanks for posting and sharing a code snippet.
I took a look at the code you shared.

Reasons why you are having problems with your Ajax Form Submission.

  1. You did not add the action attribute to your form.
  2. You registered the Submit Event listener before defining the Submit Event handler function. Therefore the event handler function is undefined.
  3. The HTML DOM element property innerHTML is NOT supposed to be a function.

Kindly make the changes to your HTML and JS code to match the code below.

For the HTML, add the action attribute to your form and set the value to "/". Note that the value of the action attribute of the form thus "/" must match the URL path in your fetch request.

<form id="contact-form" name="contact" method="POST" data-netlify="true" netlify-honeypot="bot-field" action="/">

JS Code:

const contactForm = document.getElementById("contact-form"), submitMessage = document.getElementById("contact-form-result");

const handleSubmit = (e) => {
  let formData = new FormData(contactForm);

  fetch("/", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams(formData).toString(),
    .then(() => {
      submitMessage.innerHTML = `<div class="alert alert-success alert-dismissible fade show" role="alert"><strong>Grazie!</strong> La richiesta è stata inviata, ti ricontatteremo al più presto.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>`;
    .catch((error) => {
      submitMessage.innerHTML = `<div class="alert alert-danger alert-dismissible fade show" role="alert"><strong>Errore!</strong> La richiesta non è stata inviata, per favore riprova più tardi.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>`;

contactForm.addEventListener("submit", handleSubmit);

Let me know if it works. Thanks.

Thanks a lot @clarnx for bugfixing my code and providing a fixed version.
It’s working now!
Have a nice day

1 Like

You are welcome @raffaellarinaldi. I’m glad I was able to help.

1 Like