S
S
sdgs4s4 .2018-05-07 14:45:48
JavaScript
sdgs4s4 ., 2018-05-07 14:45:48

Specifying the number of items added to the cart - how to do it?

I'll start with a picture to make it clearer.
5af03b724372f727232296.jpeg
I'm trying to specify what quantity to add to the cart, but the entire quantity is indicated only for the first product. If the first item has a quantity of 4, and the third has 1 and added the third, then 4 pieces will still be added to the third product.
How to specify the quantity by the desired product id?
- - -
Code:
View

<?php foreach ($pizza as $one): $i++?>
                            <input type="text" value="1" id="qty">
                            <a href="<?= \yii\helpers\Url::to(['cart/add', 'id' => $one->id]) ?>" data-id="<?= $one->id ?>" type="submit" class="product__button button button_primary-outline add-to-cart">
                                <span class="button__inc">В корзину</span>
                            </a>
                        <?php endforeach; ?>

$('.add-to-cart').on('click', function (e) {
        e.preventDefault();
        var id = $(this).data('id'),
            qty = $('#qty').val();
        $.ajax({
            url: '/cart/add',
            data: {id: id, qty: qty},
            type: 'GET',
            success: function(res){
                if(!res) alert('Ошибка!');
                showCart(res);
            },
            error: function(){
                alert('Error!');
            }
        });
    });

Controller:
public function actionAdd(){
        $id = Yii::$app->request->get('id');
        $qty = (int)Yii::$app->request->get('qty');
        $qty = !$qty ? 1 : $qty;
        $product = Product::findOne($id);
        if(empty($product)) return false;
        $session =Yii::$app->session;
        $session->open();
        $cart = new Cart();
        $cart->addToCart($product, $qty);
        if( !Yii::$app->request->isAjax ){
            return $this->redirect(Yii::$app->request->referrer);
        }
        $this->layout = false;
        return $this->render('cart-modal', compact('session'));
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tyzberd, 2018-05-07
@Encoderast

<input type="text" value="1" class="js-qty" id="qty">

qty = $(this).prev('.js-qty').val();

A
Arman, 2018-05-07
@Arik

1. Action through the GET method is bad
2. id in html must be unique
3. Through JS you know which link you clicked, so you can find out the neighbor input with the number

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question