Search code examples
phpajaxyii2shopping-cart

yii2 shopping cart ajax


I want to modify existing shopping cart in yii2, so it wouldn't reload the page, means make it work by ajax. Current cart looks like:

 <form method="post" id="form-prodtobuy-<?= $p->id ?>" action="<?= \Yii::$app->urlManager->createUrl(["site/cart"]) ?>">
 <input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
 <input type="hidden" name="task" value="update" />
 <input id="<?= $p->id ?>" class="form-control buy-input" name="product[<?= $p->id ?>]" value="<?= Purchase::getCartValue($p->id) ?>" data-id="<?= $p->id ?>" placeholder="0">
 <button class="btn btn-primary" type="submit">Buy <i class="glyphicon glyphicon-shopping-cart"></i></button>
 </form>

It works properly, but reloads the page.

var_dump($_SESSION); after that looks like:

 array(2) { ["__flash"]=> array(0) { } ["products"]=> array(3) { [2958]=> string(1) "2" [2959]=> string(1) "1" [2581]=> string(1) "1" } }

My obvious solution is to add e.preventDefault() on submit event as follows:

 $(document).on('submit', '[id^=form-prodtobuy-]', function(e) {
 e.preventDefault();
 var someVar = $('#someInput').val();
     $.ajax({
        type: "post",
        url: "<?php echo \Yii::$app->urlManager->createUrl(["site/cart"]) ?>",
        data: {???:someVar},
        .....................
     });
 });

What should be in ajax 'data'?
Where or how is it possible to get names of variables to set session properly?


Solution

  • In ajax "data" put form seralization output.

    Take care that I've used heredoc format, so last EOT_JS must not have spaces before it.

    $urlForm = \Yii::$app->urlManager->createUrl(["site/cart"]);
    
    $this->registerJs( <<< EOT_JS 
    
        $(document).on('submit', '[id^=form-prodtobuy-]', function(e) {
            e.preventDefault();
    
            var formData = $(this).serialize();
    
            $.ajax({
                type: "post",
                url: "{$url}",
                data: formData,
                function(data) {
                    console.log('form submit output');
                    console.log(data);
                }
            });
        });
    
    EOT_JS
    );