Forum

Thread tagged as: Runway, Shop

Adding to cart without going to the cart itself

Hello

Is there any way to do this? an ajax call maybe?

Lexi McGee

Lexi McGee 3 points

  • 4 years ago

You can call perch_shop_add_to_cart() and pass in the ID

P K

P K 0 points

Yep, ajax works great.

It was a lightbulb moment for me when I learned (from this forum) the master template for a page such as '/shop/add-to-cart' can be just the function on its own. Makes for very snappy ajax calls.

<?php

$prodId = $_POST['productID'];
$prodQty = $_POST['productQty'];

perch_shop_add_to_cart($prodId,$prodQty);

?>

Then on your product page your ajax might look something like...

$.ajax({
    method: "POST",
    url: "/shop/add-to-cart",
    data: { productID: theProductID,productQty: theProductQty }
})
.done(function( msg ) {
    $.ajax({
        url: "/shop/count",
        cache: false
    })
    .done(function( html ) {
        $( ".bag-num" ).html( html );
        openCartConfirm();
    });             
}); 

If you're going to bother with ajax, may as well go all the way and update the cart item count too, as I'm doing above. I've basically "ajax-ified" a lot of shop functions this way, including emptying cart, product wish-list feature, shipping methods... all ajax calls. And why not? It's the best user experience and allows you to display nicely designed "done" messages, green ticks, loading spinners and whatever other pretty things people expect these days.