fotant
fotant

Reputation: 63

Update cart with ajax

Hi I've made an eshop and what I want to achieve is when I click the appropriate "add to cart button" I want the top cart (not the main cart-page of the eshop) to be updated. Top cart is one div at the header of the eshop. When I refresh the page the right content appears but this doesn't happen without refresh. I know this must be accomplished with ajax but it seems I am doing something wrong.

Part of my code:

<input type="button" class="add_to_cart" id="add_to_cart" value="BUY" />
<script type="text/javascript">
    $('input.add_to_cart').click(function () {
        $.ajax({ 
            type: "POST",
            url:"add_to_topcart.php",
            data:$('.prod_form').serialize(), 
            success:function(data){
                $('#show-quick-cart').text(data); 
               $(".add_cart_msg").delay(250).fadeIn("slow").delay(2000).fadeOut("slow");
             }
         });
     });
</script>
</form>
</div>

<div class="add_cart_msg" style="display:none;"><img src="images/green_tick.png"/>Product was added to cart!</div>

The above has a result to temporarily count the products I add to cart

Upvotes: 0

Views: 959

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34426

First of all, enclose your code in a document ready handler -

$(document).ready(function() {
    $('input.add_to_cart').click(function () {
        $.ajax({ 
            type: "POST",
            url:"add_to_topcart.php",
            data:$('.prod_form').serialize(), 
            success:function(data){
                $('#show-quick-cart').text(data); 
                $(".add_cart_msg").delay(250).fadeIn("slow").delay(2000).fadeOut("slow");
            }
        });
     });
});

Then open your browser's console and any errors will be logged. You can then fix them one at a time or post them here if you need help troubleshooting.

Upvotes: 1

Related Questions