We are transitioning over to a new forum platform. Please post new issues there. Existing threads will be dealt with here unless you choose to move them over. Visit the new forum

Forum

Thread tagged as: Question, Shop

Shop cart update prices with JS

Is it possible to update the total prices within the cart via JavaScript? I am calculating hire prices for a product based on dates and am currently passing the results through to with the order using cart-property="Hire Dates" etc but was wandering if it is possible to update the actual prices associated to the order? If so how?

Many thanks!

Rob Saunders

Rob Saunders 0 points

  • 1 year ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

Yes, you'd need to create an endpoint in your site that outputs the data you need and then request that from your JavaScript.

Could you elaborate on this or point me towards some examples?

Drew McLellan

Drew McLellan 2638 points
Perch Support

I don't have any specific examples of this. Which part are you struggling with?

I dont know what you mean by 'create an endpoint in your site that outputs the data'. I have a normal cart setup which has the item data. How can I update the prices within the cart to reflect prices calculated via JS?

Currently in cart.html I have:

<td data-product-daily-price="<perch:cartitem id="price" />"><span data-product-day-count></span> £<perch:cartitem id="price" /></td>

The <td> is being passed a price via JS but I'm not sure how I then pass this price into <perch:cartitem id="price" /> to update the order data.

Duncan Revell

Duncan Revell 78 points
Registered Developer

Hi Rob,

the endpoint would usually be a php page - the sole job of this page would be to call php functions to update the cart - not outputting html or anything.

There is a shop function perch_shop_add_to_cart() (link to docs) which also allows you provide a quantity like so:

perch_shop_add_to_cart(12345, 9)  // 9 lots of product id 12345

Within your javascript code, you could send data to your endpoint like so:

http://site-domain.com/endpoint_page?product=12345&qty=9

The php page grabs those params and passes them to the function.

I don't think there is a function to change product prices, but for your example, working out the number of days and using that as a quantity of a day 'product' with associated price may suffice?

Thank you Duncan, that explains it brilliantly. Much appreciated!