cancel
Showing results for 
Search instead for 
Did you mean: 

How to make ajax request to add products in the cart ?

How to make ajax request to add products in the cart ?

So what i want to do is make request from my chatbot when we click add to cart it should add the products and i want to know how we can do that i am adding chatbot through admin panel design config add html in footer a script and div script is hosted on our side which will have all the code to show chatbot. I tried the rest api method but it wont work well as there will be csp and cors error and also auth token would be required. i came across this code , but its not working in the console. How to do it any ideas?

 

var productId = 'BU10006275'; // Replace with the actual product ID
var qty = '1'; // Desired quantity
var formKey = 'dz5mIn1nsQ4dK1ue'

// Perform the AJAX request
jQuery.ajax({
    url: '/checkout/cart/add', // Magento endpoint for adding products to the cart
    type: 'POST',
    dataType: 'json',
    data: {
        product: productId,
        qty: qty,
        form_key: formKey
    },
    success: function(data) {
        // Handle success response
        console.log('Product added to cart!', data);
    },
    error: function(xhr, status, error) {
        // Handle error response
        console.error('Error adding product to cart:', error);
    }
});