user3793282
user3793282

Reputation: 19

Add product to cart using jquery ajax not working

I am using ajax to add product in cart using code:

$cart = Mage::getModel('checkout/cart')->getQuote();
$cart->addProduct($product,array('qty'=>1));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

When I click on add to cart this adds the product(lets say CPU) successfully, then I add any other product (lets say Laptop) then it fails to add the Laptop product in cart but when i add the Laptop product second time then it is added to cart successfully. I am not able to locate the problem. Please help. Thanks in advance.

Upvotes: 0

Views: 2484

Answers (2)

Marc
Marc

Reputation: 11

In magento the add to cart process is a simple form submit process, so the page get reloaded.Therefore, Ajax based Shopping Cart comes as a solution to fasten the buying process. Step by step process: How to Add Product To Cart Using Ajax

Upvotes: 1

Karan Adhikari
Karan Adhikari

Reputation: 362

Just do onething call product add to cart link on button with url attribute like..

> <button type="button" title="<?php echo $this->__('add to cart') ?>"
> class="button btn-cart addsample" url ="<?php echo
> $this->getAddToCartUrl($_product) ?>"><span><span><?php echo
> $this->__('add to cart') ?></span></span></button></div>

Now use this ajax post.

$j('button.addsample').click(function(){
            $j(this).attr('disabled','disabled');

            $j.ajax({
                            type: "POST",
                            cache   : false,
                            dataType: 'json',
                            url: $j(this).attr('url'),
                            data: data,
                            success:function(data){

                                setTimeout(function() {
                                            window.location.reload();
                                    }, 1600);   


                                },
                            error:function(){

                                    setTimeout(function() {
                                            window.location.reload();
                                    }, 1600);   

                        }


            });

    });

Here i am sending ajax post to magento's default add to cart controller.. hope this will be helpful to you

Upvotes: 0

Related Questions