Add Products to Cart

Asked

Viewed 174 times

-1

On any site, there is a list of products and these products can be added to the cart, how could I pick up the id of these products at the user click? I thought so

<div class="products">
     <figure>
         <img src="prod_img.png" class="product_image" />
     </figure>
     <h3 class="product_name">Produto X</h3>
     <span class="product_price">R$ 99,90</span>
     <input type="submit" productId="xxxx" class="button-add" value="Adicionar ao carrinho" />
</div>

When the user clicks on the 'Add to cart' button, javascript will pick up the product id contained within the attribute productId and send it to php so that it can add the product to the cart and return the product already added (in ajax). I could also create the cart purely in javascript by adding the data into a Document.cookie and go through the div 'products' to take the image, the name, the price and the product id and add it in the cart, when the user submits the purchase, the id will be used as a reference to the product that will be rescued from the database with php. This is doubtful of beginner, but, these solutions are used in day-to-day? Or is it just a gambiarra? What is the best method for this?

1 answer

0

The ideal is that you make an ajax request by sending the product id to be added in a relational table linking the product id to your cart, in the database.

This way you can go out and enter the site and your cart will be there with the product. Many websites even use this information to send emails saying that you forgot something in your cart and asking if you don’t want to proceed with the purchase.

Therefore the idea of storing in javascript, or cookie would not be appropriate.

As for your html, I would change the input type Submit to an input type button, because Submit is to be used inside forms in common synchronous requests (with the "refresh" page).

There are several ways to organize this, always think about the most semantic (understandable to those who have never touched your code) and more scalable (organized, with well defined functions and no duplicate codes).

  • Thanks for taking my question and give me this tip of the 'Ubmit' input, I don’t have much experience with front.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.