简体   繁体   中英

Open modal cart after cart is updated

I want to add two different products (A & B) to the cart with one "Add to cart" button while beeing on product page A. Each product has custom properties that also need to be transmitted to the cart. We use the "modal" cart option.

Found this piece of code on github :

var MGUtil = {
    data: [],
    ini: 0,
    total: 0,
    addItem: function(qty, id, properties, callback) {
        var params = { quantity: qty, id: id };
        if (properties != false) {
            params.properties = properties;
        }
        $.ajax({
            type: 'POST',
            url: '/cart/add.js',
            dataType: 'json',
            data: params,
            success: function() {
                if (typeof callback === 'function') {
                    callback();
                }
            },
            error: function() {}
        });
    },

    recursive: function() {
        MGUtil.addItem(MGUtil.data[MGUtil.ini].qty, MGUtil.data[MGUtil.ini].id, MGUtil.data[MGUtil.ini].properties, function() {
            MGUtil.ini += 1;
            if (MGUtil.ini < MGUtil.total) {
                MGUtil.recursive();
            } else {
                document.location.href = '/cart';//GO TO THE CART AFTER ADDING ITEMS
            }
        });
    },

    begin: function() {
        /*SAMPLE*/
        /* SET YOUR ARRAY QTY's' ID's PROPERTIES(FALSE IF IS EMPTY)*/
        MGUtil.data = [
            { "id": "#variant_id_A", "qty": 2, "properties": { "data1": "1" } },
            { "id": "#variant_id_B", "qty": 3, "properties": { "data2": "1" } }
        ];
        MGUtil.total = MGUtil.data.length;
        MGUtil.recursive();
    }
}

MGUtil.begin();

Only thing missing is that i want to open the "modal" cart and not go to the cart page.

I can show the cart with:

$('#ajaxifyModal').addClass('is-visible');

but the content is not updated when i do that on the product page after running the code above. Refreshing the page would be one solution - not very pretty one though.

How can i update the cart content and open the modal cart while not leaving the page?

Update

Think this is the AJAX call to receive the updated cart content:

$.ajax({
    type: 'GET',
    url: '/cart.js',
    dataType: 'json',
    success: function(cart) {
        console.log(cart);
    },
    error: function() {}
});

try replace your "else" with this one here

else {
  var tmpVar = $.get("/cart"); // trying to trigger the page (we are not going to do anything with this variable)
  $('#ajaxifyModal').addClass('is-visible'); // open the modal
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM