There is a set of products and you need to add all the goods in the kit to the cart. Now I add the product like this:

<a style="cursor:pointer" class="btn-buy" onclick="addCart(this);">Купить</a> <input type="hidden" value="<?=$produсt->id?>" name="id"/> 

When you click on "Купить" , the addcart function is addcart , to which one product id is sent.

 function addCart(btn) { $this = $(btn); var id = $this.siblings('input[name=id]').val(); $.ajax({ url: '/cart/add_cart', dataType : "json", type : 'post', data : { 'id':id }, success: function (data, textStatus) { $(".total_count").text(data.total_count + " шт."); $(".sum").text(data.total_price); $('.name_modal').html(data.addProduct.title); $('.price_modal').html(data.addProduct.price); $('.img_modal').attr('src', '/' + data.addProduct.img); $('#myModal').reveal({}); } }); } 

But how to add a few products when you click on "Купить" ? An example for you to understand what a kit is. Below the product is shown kit. I want to add a "Купить" button, and so that all the items in the kit are added to the cart.

  • one
    Why don't you make an extra button to buy a kit? And through it to transfer aydishniki all in a kompletke To transfer json-th array to the model and form the basket in this way. - Kirill Korushkin

1 answer 1

I usually in such cases use the form + serialize + eventpreventdefalt + ajax (or rather, his younger brother)

 $('form').submit(function(event) { event.preventDefault() $.post('/cart/add_cart',{ 'act':'add_to_bascket' ,'data':$(this).serializeArray() },function(data){ $(".total_count").text(data.total_count + " шт."); $(".sum").text(data.total_price); $('.name_modal').html(data.addProduct.title); $('.price_modal').html(data.addProduct.price); $('.img_modal').attr('src', '/' + data.addProduct.img); $('#myModal').reveal({}); }); }); 

ajax is better, of course, because in case of failure it can re-send it or inform the user about an alternative option to $ .post (); worked necessary to connect the jquery library.

My answers are usually minus and do not explain why - maybe this will be my last answer, I will be glad if it helped.

  • It is not necessary to use the $ ('form'). submit event (you can have another, the main thing here is $ ('form'). serializeArray (), and an unlimited quantity of goods can be in the form - Mcile