1

Hi this is a variation of the question asked here on updating the cart using ajax, instead I'm attempting to use the Fetch API. As a test the form submits properly when submitting in the usual way without using the Fetch request. I've attempted to replicate the synchronous request header that I inspected in the Chrome Network tab but I still get a Bad Request error.

HTML:

<form method="POST" id="addToCartForm">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="/cart">
    <input type="hidden" name="purchasableId" value="{{ product.id }}">
    <input type="number" name="qty">
</form>

JS:

let formElem = document.getElementById('addToCartForm');
let form = new FormData(formElem);
let request = new Request('/', {
  credentials: 'include',
  method: 'post',
  mode: 'same-origin',
  redirect: 'follow',
  headers: new Headers({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'X-Requested-With': 'XMLHttpRequest' // so craft detects ajax
  }),
  body: form
});

fetch(request).then((response) => {
  if(response.ok) {
    return response.text();
  }
  throw new Error('Network response was not ok.');
}).then((response) => {
  console.log('Worked:');
  console.log(response);
}).catch((error) => {
  console.log(error);
});

2 Answers 2

2

The problem was resolved by changing the headers set:

let form = new FormData(this.form);
let request = new Request('/', {
  credentials: 'include',
  method: 'post',
  mode: 'same-origin',
  redirect: 'follow',
  headers: new Headers({
    'Accept': '*/*',
    'X-Requested-With': 'XMLHttpRequest'
  }),
  body: form
});

Instead of declaring the Content-Type in the request, I set the encoding type on the form itself, this step is optional as the request sets as multipart/form data by default I think.

<form method="post" enctype="multipart/form-data">
..
</form>
1

As mentioned on Twitter, pretty sure this we will be an issue with CSRF ... Get it working first with that turned off is my advice. I have not used Fetch, though.

0

Your Answer

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

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