0

I created a list of products from AJAX response in phtml file. In that case default AJAX "ADD TO CART" is not working. Can anyone suggest me how I can create a ajax based add to cart for products list?

0

Finally, I have an solution for my problem. Here I am posting my solution. I hope it will help others people too.

This is my custom 'add to cart' form code, I am getting this code in my custom AJAX product listing:

<form id="product_addtocart_form_guide0" action="" method="post"> 
    <input name="add_to_cart_url" id="add_to_cart_url" value="http://yourDomain.com/checkout/cart/add/uenc/aHR0cDovL2RlYWR3b29ka25pdmVzLmdyYXppdHRpLmNvbS9mYW5jeWZlZWRiYWNrL2luZGV4L2d1aWRlLw,,/product/2799/" type="hidden">
    <input id="product_id" name="product" value="2799" type="hidden">
    <input id="form_key" value="4D6nofdiNG194XG1" name="form_key" type="hidden">
    <div class="actions">
    <button title="Add to Cart" class="action tocart btn btn-default btn-cart" id="product-addtocart-button1">
        <span>Add to Cart</span></button>
    </div>
</form>

This is solution. I added this script in my 'phtml' file for AJAX add to cart:

<script type="text/javascript">
    jQuery(document).on('click', '#product-addtocart-button1', function(e) {
        e.preventDefault();
        var post_url = jQuery(this).closest("div").find("input[name='add_to_cart_url']").val();
        var data = jQuery(this).closest('div form').serialize();
        try {
            jQuery.ajax({
                url: post_url,
                dataType: 'json',
                type : 'post',
                data: data,
                success: function(data){
                    <!-- add success action here --> 
                }
            });
        } catch (e) {
        }
        return false;
    });
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.