Submitting customer form asynchronously

OliverG1
Visitor
1 0 0

Hello, we're having problems implementing a newsletter form on the footer of our site. We'd like to post the form asynchronously using fetch, but keep getting the same error: Failed to create customer with a 400 (Bad Request). 

 

Here's the code we're using:

<form id="signup-form" 
  accept-charset="UTF-8" 
  class="contact-form15">
  <input type="hidden" name="form_type" value="customer">
  <input type="hidden" name="utf8" value="✓">
  <div class="email">
    <label for="email">Email</label>
    <input type="email" name="contact[email]" id="email" required="">
  </div>
  <div class="submit">
    <input type="submit" value="Submit">
  </div>
</form>


<script>
  const form = document.querySelector('#new-signup-form');

  form.addEventListener('submit', handleForm );

  function handleForm(evt){
    evt.preventDefault();

    const fd = new FormData(evt.target);
    
    const url = '/contact#signup-form'
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'        
      },
      body: fd
    })
    .then(function(response){
      if(!response.ok) {
        throw new Error('Failed to create customer');
      }
      return response.json();
    })
    .then(function(data){
      console.log('Customer crated: ', data.customer);
    })
    .catch(function(error){
      console.log('error: ', error);
      console.error('Error creating customer:', error.message);
    });

  }
</script>

Any help is appreciated!

Replies 0 (0)