robins
robins

Reputation: 1668

Cart data is not updating using Ajax

I'm trying to do a Codeigniter cart.

I got some issues in updating cart details.

HTML/VIEW

foreach ($cart as $item){ 
$output.='
      <input type="hidden" name="cart[' . $item['id'] . '][rowid]" value="'.$item['rowid'].'" >
      <input type="hidden" name="cart[' . $item['id'] . '][name]" value="'.$item['name'].'" >
      <input type="hidden" name="cart[' . $item['id'] . '][price]" value="'.$item['price'].'" >
      <input type="hidden" name="cart[' . $item['id'] . '][qty]" value="'.$item['qty'].'" >
    ';

}
<input type="submit" class="btn btn-info btn-sm" value="Update Cart" onclick="update_cart();">

These hidden fields contain all the data to be updated.

JS

 function update_cart() {
    var cart = new Array();
    $('input[name^="cart"]').each(function() {
        cart.push($(this).val());
    });
    $.ajax({
        url: base_url + 'test/update_cart',
        data: {
            cart: cart,
            csrf_test_name: csrf_token
        },
        type: "POST",
        ,
        success: function(data) {
        }
    });
}

CONTROLLER

function update_cart() {
    $cart_info = $_POST['cart'];
    foreach($cart_info as $id => $cart) {
        $rowid = $cart['rowid'];
        $price = $cart['price'];
        $amount = $price * $cart['qty'];
        $qty = $cart['qty'];
        $data = array(
            'rowid' => $rowid,
            'price' => $price,
            'amount' => $amount,
            'qty' => $qty
        );
        $this - > cart - > update($data);
    }
}

Upvotes: 0

Views: 129

Answers (1)

Exprator
Exprator

Reputation: 27503

 function update_cart(){
        var cart = new Array();
        $('input[name^="cart"]').each(function() {
          cart.push($(this).val());
    });
       $.ajax({
                url: base_url + 'restaurant/update_cart',
                type: "POST",
                data: {
                    'cart':cart,
                    'csrf_test_name': csrf_token
                },

                success: function(data) {

                    }

        });

    }

change your ajax to this

Upvotes: 1

Related Questions