Developer forum

Forum » Ecommerce - Standard features » Empty cart and add to cart in same URL

Empty cart and add to cart in same URL

Rune Skovbo
Reply

Hi people

I need to be able to empty the cart and then add a product to it, on the same click.

I need to be sure that only the latest product added to the cart is actually in the cart.

Something like: <a href="?CartCmd=EmptyCart&Redirect=<!--@Global:Pageview.Url.Raw-->&CartCmd=Add">Submit</a>, but this doesn't seam to work. Maybe because of the two "CartCmd" in the same URL?

Has anyone got a good (frontend-programming) solution to this?

 

/Rune


Replies

 
Aki Ruuskanen
Reply

Hi,

Maybe an ajax call first with CartCmd=EmptyCart and then the call to add a product.

/Aki

 
Mikkel Ricky
Reply
This post has been marked as an answer

You need two calls for this: one that empties the cart and one that add the current product to the cart.

One way to do this (using jQuery) is like this

<button id="onlyThisInCart">Only this in cart</button>
<script>(function($) {
    var url = '<!--@Global:Pageview.Url.Raw.JSEncoded()-->';
    $('#onlyThisInCart').on('click', function () {
        // Empty the cart
        $.post(url, {
            'CartCmd': 'emptycart'
        })
            .done(function() {
                // Add current product to cart. Assumes that productId is in current url
                // Note: we should actually make a POST when adding the product, but it's just an example
                document.location.href = url+(url.indexOf('?') < 0 ? '?' : '&')+ 'CartCmd=add';
            })
    });
}(jQuery))</script>

Best regards,
Mikkel

Votes for this answer: 2
 
Rune Skovbo
Reply

Hi Mikkel

Works like a charm!

Thanks a lot!

/Rune

 

You must be logged in to post in the forum