I have converted following script from jquery based Ajax to Pure javascript-based Ajax but it is not working
here is Jquery based script
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json'
});
}
}
Here is converted Javascript code
function addCart(elements, product_id, quantity) {
// Creating the XMLHttpRequest object
var request = new XMLHttpRequest();
// Instantiating the request object
request.open("POST", "/index.php?route=checkout/cart/add", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
// 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");
}
};
var data = 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1);
// Sending the request to the server
request.send(data);
}
I think there might be a problem in sending data as I am not that much aware of it.
I changed HTML from
<button type="button" onclick="cart.add('{{product_id }}', '{{minimum }}');">Add</button>
to
<button type="button" onclick="addCart(this, '{{product_id }}', '{{minimum }}');">Add</button>
In order to send a form encoded message in JS, you either need to submit a form or create a FormData object. In your case, we will be creating a 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);
Now, I would recommend using the new fetch API instead of using XMLHttpRequest. So, your request would look something like the following code.
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.');
});
It is on my opinion, much easier to understand and it is easier to translate from jQuery, because of the similar structure.
So, doing all the corresponding changes, your method would end up looking like this.
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.');
});
}
If fetch is not allowed, because of browser compatibility, we can still use XMLHttpRequest. Your code would just need some minor changes.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With