2

I'm working on a site that has recently migrated from Craft v2 with Commerce v1 to Craft v3 with Commerce v2.

Using Commerce v1 I was able to update the cart via Ajax and get a data object with the state of the cart as a response.

After updating to Craft Commerce v2 the ajax requests fail, returning Status 302 - Redirect instead of the data object, although the changes to the cart are successful.

I can add one or more products or change their quantity via Ajax, however, I need the data object in order to properly update the state of the cart without reloading the page.

  • I'm running Craft v3.0.10.2 with Craft Commerce from dev-develop commit 1db58f6 on a machine running PHP v7.1.12
  • The action I'm using is commerce/cart/update-cart
  • The method of all requests is POST
  • Any form data should to be ok since the cart updates succesfully
  • All requests are sent with the following headers: Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest

I'm I missing anything new in CC2? Any help would be much appreciated.

1 Answer 1

5

The function contains this

if ($request->getAcceptsJson()) {

Thus you'll need to set the dataType in your ajax request to json or text/json in order to not get redirected. If you didn't set it correctly Craft will treat it as a normal post request instead of an ajax request

2
  • Thank you so much! That fixed it. I had no idea CC2 was doing such a check. Jun 8, 2018 at 13:31
  • Nearly all Craft 3 controllers have this condition. So should keep it in mind Jun 8, 2018 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.