Чтобы отправить закодированное сообщение формы в JS, необходимо либо отправить форму, либо создать объект FormData
. В вашем случае мы будем создавать FormData
.
// Set the needed params.
let formData = new FormData();
const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
formData.append('product_id', product_id);
formData.append('quantity', finalQuantity);
Теперь я бы рекомендовал использовать новый fetch API
вместо XMLHttpRequest
. Итак, ваш запрос будет выглядеть примерно так:
fetch('index.php?route=checkout/cart/add', {
method: 'POST',
body: formData,
}))
.then(response => response.json())
.then(() => {
console.log('Success.');
}).catch(error => {
console.log(error.message);
}).finally(function () {
console.log('Something you wanna execute even if you caught an error or if the request was successful.');
});
На мой взгляд, его гораздо проще понять и легче перевести с jQuery из-за схожей структуры.
Таким образом, при внесении всех соответствующих изменений ваш метод в конечном итоге будет выглядеть следующим образом.
function addCart(element, product_id, quantity) {
// Set the needed params.
let formData = new FormData();
const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
formData.append('product_id', product_id);
formData.append('quantity', finalQuantity);
fetch('index.php?route=checkout/cart/add', {
method: 'POST',
body: formData,
}))
.then(response => response.json())
.then(() => {
console.log('Success.');
}).catch(error => {
console.log(error.message);
}).finally(function () {
console.log('Something you wanna execute even if you caught an error or if the request was successful.');
});
}
Если fetch
не разрешен, из-за совместимости браузера мы все равно можем использовать XMLHttpRequest
, Ваш код просто нуждается в небольших изменениях.
function addCart(elements, product_id, quantity) {
// Build the form data.
let formData = new FormData();
const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
formData.append('product_id', product_id);
formData.append('quantity', finalQuantity);
// Creating the XMLHttpRequest object
const request = new XMLHttpRequest();
// Instantiating the request object
request.open("POST", "/index.php?route=checkout/cart/add");
// Defining event listener for readystatechange event
request.onreadystatechange = function() {
// Check if the request is compete and was successful
if(this.readyState === 4 && this.status === 200) {
alert("Success");
}
};
request.send(formData);
}