0

I have a simple shopping cart system and I am using JQuery to update the cart items as a user navigates around the website.

The problem I face is that the delete function does not work after the user has re-added some products to the shopping system. Only after a page refresh does it start to work again and then stops once the user adds more products...

The story goes like this:

  1. Product page loads,
  2. User clicks on products to add to basket,
  3. JQuery adds the products on each click to the server via ajax, on success the shopping cart HTML is updated with a fresh set of products (I do not append to the list, just grab all items and re-add).
  4. User decides to remove products by opening the cart modal, and clicks on the respective items.
  5. Items are removde as expected. Jquery is removing each li individually at this point.
  6. User decides to add further products, works perfectly.
  7. User decides to delete products... And this is where it dies...

Here is the code dealing with the delete:

/**
 * Delete an item from the cart
 */

$('.del-goods').click(function(){
    var itemId  = $(this).data("item");
    var url = "/cart/delete/item_id/" + itemId;

    $('#item-delete-' + itemId).html('<div style="color:red;">Deleting...</div>');

    //Set up Ajax to update the customers cart
    $.ajax({
        type:  'POST',
        async: true,
        url:   url,
        dataType: "json",

        success: function(responseObject){
            //If the response is successful
            if (responseObject.success)
            {
                $('.cart-info-count').text(responseObject.cart_item_count);
                $('.cart-info-value').text(responseObject.cart_item_total);
                $('#item-' + itemId).remove();
            } else {
                alert("Failed to delete item!");
            }

        }
    });

});

The following is my add to cart functionality. I suspect the problems are caused when I pull a new fresh set of drop down items which includes the delete link...

 $('.add2cart').click(function() {

    //The click event relating to the add product area
    var productId  = $(this).data("product");
    var area       = $(this).data("area");

    //Get the product quantity
    var quantity   = $('#' + area).find('input[name="productQuantity"]').val();

    //Make sure the quantity is an integer and not a float
    if ( Math.floor(quantity) != quantity)
    {
        quantity = 1;
    }

    //Make sure the quantity is numeric and not characters
    if ( ! $.isNumeric(quantity) )
    {
        quantity = 1;
    }

    //If quantity is zero, make it 1
    if ( quantity == 0 )
    {
        quantity = 1;
    }

    //Controller Route
    var url = '/cart/update-quantities/prod_id/' + productId + '/quantity/' + quantity;

    //Change the icon text to processing...
    $('#' + area).find('.add2cart').text('Processing...');

    //Update the datbase with the new cart item
    $.ajax({
        type:  'POST',
        async: true,
        url:   url,
        dataType: "json",

        success: function(responseObject){
            //If the response is successful
            if (responseObject.success)
            {
                //Write success to the clicked button
                $('#' + area).find('.add2cart').text('SUCCESS...');

                //Reset button to original state
                window.setTimeout(function () {
                    $('#' + area).find('.add2cart').text('ADD TO CART');
                }, 1500);

                //Update the view with the correct items in the cart
                $('.cart-info-count').text(responseObject.cart_item_count);
                //Update the view with the new cart total
                $('.cart-info-value').text(responseObject.cart_item_total);
                //Update the HTML (this pulls a whole fresh set of HTML)
                $('#cart-dropdown').html(responseObject.cart_item_dropdown_html);

            } else {
                //Write failed to the clicked button
                $('#' + area).find('.add2cart').text('FAILED...');

                //Reset button to original state
                window.setTimeout(function () {
                    $('#' + area).find('.add2cart').text('ADD TO CART');
                }, 1500);
            }

        }
    });

});
HappyCoder
  • 5,985
  • 6
  • 42
  • 73
  • 2
    instead of ussing click, try using on http://api.jquery.com/on/ – chepe263 Jan 01 '15 at 23:12
  • @chepe263 whilst valid advice, it's in no way relevant to the OP's problem (unless you're also suggesting he needs to use the delegated version, but didn't say so) – Alnitak Jan 01 '15 at 23:13
  • Why are you using classes instead of unique identifiers? (.cart-info-count, .del-goods) Are there more than one of these elements? – Steve Wellens Jan 01 '15 at 23:16
  • @SteveWellens for .del-goods, there are multiple items. These appear in the li. Obviously a class is best for this. .cart-info-count could be an ID tag... – HappyCoder Jan 01 '15 at 23:19
  • @Alnitak My english no good. Hard to explain big concept. I will try best my next chance. – chepe263 Jan 02 '15 at 03:50

1 Answers1

1

You have to use event delegation as the content are dynamically changed.

$(document).on('click','.del-goods',function(){
noob
  • 138
  • 1
  • 2
  • 8