Email Subscription

Hello everyone!

I have liquid code for shopify website that does following:
It displays email input field and a submit button where customers can write down their email and click on submit button (shown as subscribe) and their email addresses are
stored in shopify customers list. The problem with my code is that page is refreshed. I want a smooth flow when users click on “'Subscribe“ button, page refresh does not occur. I need a solution via AJAX request. How do I do it?
Any help will be appreciated. Thanks

Hi @ramsha1

Hi! Good question — this happens because the form is submitted normally, so the browser refreshes the page by default.

To avoid the page refresh, you’ll need to prevent the default form submission and send the data using **AJAX (fetch)**instead. Shopify supports this for customer creation/newsletter signup.

Below is a simple example you can adapt.

<form id="newsletter-form">
  <input 
    type="email" 
    name="contact[email]" 
    placeholder="Your email" 
    required
  >
  <button type="submit">Subscribe</button>
</form>

<div id="newsletter-message"></div>

<script>
document.getElementById('newsletter-form').addEventListener('submit', function(e) {
  e.preventDefault(); // stop page refresh

  const form = e.target;
  const formData = new FormData(form);

  fetch('/contact', {
    method: 'POST',
    body: formData,
    headers: {
      'Accept': 'application/json'
    }
  })
  .then(response => {
    if (response.ok) {
      document.getElementById('newsletter-message').innerText =
        'Thanks for subscribing!';
      form.reset();
    } else {
      throw new Error('Something went wrong');
    }
  })
  .catch(() => {
    document.getElementById('newsletter-message').innerText =
      'Please try again later.';
  });
});
</script>

When I add email address and click “Subscribe“ button, it is says “Please try again later“.

It says “Response body: {“errors”:“Missing CAPTCHA token”}“

Use Shopify Forms app instead.

Shopify has a limit on how many subscriptions per day you can submit per ip/email and then you will hit the captcha.

As you’ve already experienced. So the code may work fine for your visitors but is PITA to develop/test.

Can i add custom css Shopify Forms app?

Yes, you can push your CSS into Shopify forms, but not directly.
It needs a small Javascript work-around: