Search code examples
phpjqueryhtmlcodeigniter-3shopping-cart

Does not allow same product more than a one-time CodeIgniter shopping cart


I am using the CodeIgniter shopping cart and below is the code which displaying my all the details on the browser.

(Just share the logic part)

<?php
   foreach ($post as $row) {?>
  <tr>
    <td><?php echo $i++;?></td>
    <td><?php echo $row->name;?></td>
    <td><?php echo $row->price;?></td>
    <td>
      <?php if($row->is_approved==1){?><button type="button" name="renew" class="btn btn-success add_cart">Add to cart</button>
      <?php }else{?>
      <div class="activity_status">Not Approved</div>
      <?php };?>
    </td>
  </tr>

  <div id="primarycart_details"></div>
  <?php}?>

I am getting the output on the browser

    Id | Name   | price  | Action
    1  | poimjh | 10     | Add to cart
    2  | asdasd | 100    | Add to cart
    3  | dgfdfw | 50     | Add to cart
    4  | qwewqe | 100    | Not Approved
   // and so on

Now My issue is, When I clicked on add to cart it's adding the product details in the cart and also I am changing the button status from Add to cart to Remove. Now When I refresh the page then my button again change from Remove to Add to cart. I don't want to add the same product more than one time.

Ajax

    $(document).ready(function(){
  $(document).on('click', '.add_cart', function() {
  var product_name = $(this).closest('tr').find('.productname').text();
  var product_id = $(this).closest('tr').find('.productid').val();
  var product_price = $(this).closest('tr').find('.calActivitylPrice').text();
      var quantity =1;
       $.ajax({
        url:"<?php echo base_url(); ?>Member_controller/addToCart",
        method:"POST",
        data:{product_id:product_id, product_name:product_name, product_price:product_price,quantity:quantity},
        success:function(data)
        {
            var obj = JSON.parse(data);
          //alert(data);
         $('#changeToRemove').html('<button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'+obj.removebtn+'">Remove</button>')
         $('#primarycart_details').html(obj.subtotal);
        }
       });
     });
    });

Remove code

$(document).on('click', '.remove_inventory', function(){
  var row_id = $(this).attr("id");
  //alert(row_id);
  if(confirm("Are you sure you want to remove this?"))
  {
   $.ajax({
    url:"<?php echo base_url(); ?>Member_controller/Removecart",
    method:"POST",
    data:{row_id:row_id},
    success:function(data)
    {
     alert("Product removed from Cart");
    }
   });
  }
  else
  {
   return false;
  }
 });

Remove from a cart in controller

public function Removecart(){
 $row_id = $_POST["row_id"];
 //echo $row_id;
  $data = array(
   'rowid'  => $row_id,
   'qty'  => 0
  );
  //print_r($data);
  $this->cart->update($data);
  echo $this->viewCart();

}

Add to cart code in controller

public function addToCart(){
  $data = array(
   "id"  => $_POST["product_id"],
   "name"  => $_POST["product_name"],
    "qty"  => $_POST["quantity"],
   "price"  => $_POST["product_price"]
  );
  //print_r($data);
  $this->cart->insert($data); //return rowid 
  //echo $this->viewCart();
}

Can anyone help me out on this issue?


Solution

  • You could make a conditional within the product loop like this :

    <?php
    foreach ($post as $row) {?>
    <tr>
        <td><?php echo $i++;?></td>
        <td><?php echo $row->name;?></td>
        <td><?php echo $row->price;?></td>
        <td>
        <?php if($row->is_approved==1){
            if (in_array($row->id, array_column($this->cart->contents(), 'id'))) {
                $rowid = 0;
                foreach ($this->cart->contents() as $product) {if ($product['id'] === $row->id) { $rowid = $product['rowid']; break;}}
                ?>
            <button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="<?php echo $rowid; ?>">Remove</button>
            <?php } else { ?>
            <button type="button" name="renew" class="btn btn-success add_cart" data-productname="<?php echo $row->name; ?>" data-price="<?php echo $row->price;?>" data-productid="<?php echo $row->name_id; ?>" />Add to cart</button>
            <?php } ?>
        <?php }else{?>
        <div class="activity_status">Not Approved</div>
        <?php };?>
        </td>
    </tr>
    
    <div id="primarycart_details"></div>
    <?php
    }
    

    First array_column($this->cart->contents(), 'id') is used to get an array list of product id, then apply in_array() on it to check whether current cart item is exist on product list or not.

    And this line : foreach ($this->cart->contents() as $product) {if ($product['id'] === $row->id) { $rowid = $product['rowid']; break;}} is used to look up rowid value on each product.