Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more

Submitting customer form asynchronously

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)