Shopify / starter-theme

The Shopify Themes Team opinionated starting point for new a Slate project
MIT License
481 stars 285 forks source link

Triggering product form submit via JavaScript results in error (but clicking add to cart works as expected) #171

Open cfxd opened 4 years ago

cfxd commented 4 years ago

This may be down to my mediocre JavaScript skills, but I'm struggling to figure out why triggering a submit event on the default product form results in an Oops! page from Shopify with the message Parameter Missing or Invalid: Required parameter missing or invalid: items (see screenshot below, too).

Steps to reproduce:

  1. Visit product page on new Slate install
  2. Open console and run document.querySelector('.shopify-product-form').submit();

Best I can tell, triggering the even in this way results in the theme script not executing _setIdInputValue(), but I'd like to understand why or know a better way to trigger submit.

My overall goal is to pause form submission, then add an item to cart using AJAX in the background, and upon completion, resume form submission and add the original product to the cart.

I'm using the latest Slate and have updated all of my deps. Any insight would be much appreciated.

image

Cam commented 4 years ago

Your form isn't sending the necessary variant ID to the cart.

@cfxd take a look at #128

cfxd commented 4 years ago

@Cam you're correct, except that if I click then it sends the variant ID to the cart because it fires _setIdInputValue() in theme-product-form.js.

However, if I simply try running document.querySelector('.shopify-product-form').submit(); from within another function—let's say, after preventing the default submit event—then I get the error because _setIdInputValue() doesn't run for some reason, despite being part of the submit event listener.

I'm trying to figure out how I can submit the form within another function using the submit() method or something similar.

I've been able to somewhat get it working by creating and dispatching my own custom event, but I'm thinking/hoping there's a more elegant solution.

npvk commented 4 years ago

Any fix?

cfxd commented 4 years ago

@npvk https://github.com/Shopify/starter-theme/pull/172

npvk commented 4 years ago

Thanks! 👍