Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Agregue todas las variantes y cantidades de productos al carrito con AJAX en la tienda Shopify

En mi tienda Shopify en la página del producto, tengo una tabla con el título de la variante, el precio y la columna de cantidad de entrada. ¿Puedo agregar al carrito toda la cantidad de entrada para cada variante del producto con AJAX?

mi mesa:

 <form action="/cart/add" method="post" > <tr> {% for variant in product.variants %} {% assign variant = product.selected_or_first_available_variant %} <td>{{ variant.title }}</td> <td>{{ variant.price | money }}</td> <td> <input name="quantity" inputmode="numeric" value="0"> </td> {% endfor %} </tr> <input type="submit" value="Add to cart"> </form> <script> let addToCartForm = document.querySelector('form[action="/cart/add"]'); let formData = new FormData(addToCartForm); fetch('/cart/add.js', { method: 'POST', body: formData }) .then(response => { return response.json(); }) .catch((error) => { console.error('Error:', error); }); </script>

Y alguna documentación de Shopify https://shopify.dev/api/ajax/reference/cart#post-cart-add-js

Estoy tratando de agregar al carrito todas las variantes de productos para una llamada con AJAX y obtengo:

Falta el parámetro obligatorio o no es válido: elementos

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Resumen: el envío de su formulario contiene cantidades pero no productos. También debe incluir los ID de las variantes.


En su bucle for, ha creado cuadros de cantidad para todas las variantes del producto, pero faltan los ID de las variantes. Cuando publica esos datos en /cart/add.js , Shopify no tiene forma de saber qué productos está tratando de poner en el carrito.

Para agregar varios artículos al carrito a la vez, recomendaría echar un vistazo a la documentación de Shopify para la API del carrito: https://shopify.dev/api/ajax/reference/cart#post-cart-add-js

Para agregar varios artículos al carrito, debemos enviar un campo llamado items como una matriz de objetos que especifican los ID para agregar y, opcionalmente, sus cantidades y cualquier propiedad de línea de artículo que estemos adjuntando.

Aquí hay una idea rápida sobre cómo podría verse el código resultante:

 <form class="custom-product-form" action="/cart/add" method="post"> <table> {% for variant in product.variants %} <tr> <td>{{ variant.title }}</td> <td>{{ variant.price | money }}</td> <td class="item-submission"> <!-- Added hidden input for the variant ID --> <input type="hidden" name="id" value="{{ variant.id }}"/> <input name="quantity" inputmode="numeric" value="0"> </td> </tr> {% endfor %} </table> <input type="submit" value="Add to cart"> </form> <script> let addToCartForm = document.querySelector('.custom-product-form'); addToCartForm.addEventListener('submit', (evt) => { evt.preventDefault(); // Update to create an object based on the multiple input rows let items = []; let rows = evt.currentTarget.querySelectorAll('.item-submission'); for(let i=0; i<rows.length; i++) { // Get the variant ID and quantity for each row. let itemData = rows[i]; let id = parseInt(itemData.querySelector('[name="id"]').value ); let qty = parseInt(itemData.querySelector('[name="quantity"]').value ); // We don't care about any rows with a quantity of 0 if(id && qty > 0){ items.push({ id: id, quantity: qty }); } } if(!items.length){ // Do something to tell the customer that there's nothing to add if all quantities were 0 return; } return fetch('/cart/add.js', { method: 'POST', body: JSON.stringify({ items: items }), headers: { 'Content-type': 'application/json' }, credentials: 'include' // Note: Including credentials sends the cart cookie, which is important to make sure that the items go into the shopper's cart and not into a void }) .then(response => { return response.json(); }) .catch((error) => { console.error('Error:', error); }); }) </script>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!