0

I have an embedded Mailchimp signup form which I want to process via AJAX. I've followed the top answer from this question (AJAX Mailchimp signup form integration) to make edits to the HTML form markup, however I don't use jQuery in my project so I tried to make it work with vanilla JavaScript:

<form action="https://gmail.us6.list-manage.com/subscribe/post-json?u=XXX0&amp;id=XXX&amp;c=?" method="get" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>...</form>
const form = document.querySelector('#mc-embedded-subscribe-form');

form.addEventListener('submit', (e) => {
  e.preventDefault();

  fetch(e.target.action, {
    method: e.target.method,
    mode: 'no-cors',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log(data);
    });
});

which results in the following error in the console:

Uncaught (in promise) SyntaxError: Unexpected end of input

The jQuery solution works just OK though. Any ideas?

sdvnksv
  • 9,350
  • 18
  • 56
  • 108

1 Answers1

0

The action url results in 404.

Therefore, this is the response.json(); that throws the Unexpected end of input.

To avoid the Uncaught error, catch it using a catch() block after the last then().

let form = document.querySelector("form");

form.addEventListener("submit", (e) => {
  e.preventDefault();

  fetch(e.target.action, {
    method: e.target.method,
    mode: "no-cors",
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("Request failed.");  // Custom message on the error to throw
      } else {
        return response.json();  // Call .json() only on good responses
      }
    })
    .then((data) => {
      console.log("data: " + data);
    })
    .catch((error) => {  // Catch the error here
      console.log("error: "+error);
    });
});
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64