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>
application/json, instead ofapplication/x-www-form-urlencoded; charset=UTF-8.$('#cart > ul').load('index.php?route=common/cart/info ul li');to plain JS