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);
});