Search code examples
javascriptphpajaxcodeignitercart

Codeigniter javascript function keeps failing


So i'm coding a donation store inside of codeigniter. I've been working to add the cart function to it, and have made a small card that holds the items for the store, with the ability to add to cart, and a ajax request to post and reload. The thing is, in the first category, it will work fine, success and succesfully adds to cart and reloads. but if i go into the other categories and click on an item, it always returns failure.

        <div class="card">
        <div class="card-header p-2">
            <ul class="nav nav-pills">
                <?php foreach ($category as $cat) { ?>
            <li class="nav-item">
            <a class="nav-link" href="#<?= $cat['categ_name']; ?>" data-toggle="tab"><?= $cat['categ_name']; ?></a></li>
                <? } ?>
            </ul>
        </div><!-- /.card-header -->
    <div class="card-body">
        <div class="tab-content">
            <?php foreach ($category as $pane) { ?>
        <div class="tab-pane" id="<?= $pane['categ_name']; ?>">
            <div class="row">
            <?php foreach ($item as $ditems) { ?>
                <?php if ($ditems['categ_name'] == $pane['categ_name']) { ?>
                    <div class="col-lg-3 col-6">
                        <div class="flip-card">
                            <div class="flip-card-inner">
                                <div class="flip-card-front">
                                <img src="<?= base_url() ?>assets/itemdb/<?= $ditems['image']; ?>" alt="Image" style="width:200px;height:160px;">
                                <h3><?= $ditems['item_name']; ?></h3>
                                </div>
                            <div class="flip-card-back">
                            <p><b>Price : $<?= $ditems['price']; ?></b></p>
                            <p><?php if ($ditems['package'] == 1) { ?>
                            <a href="">Package Details</a>
                            <?php } else { ?>
                            <p>Quantity : x <?= $ditems['amount']; ?></p>
                            <?= $ditems['descr']; ?></p>
                            <?php } ?>
                        <?php echo form_open(base_url('donation/add_cart_item'), 'class="horizontal-form" '); ?>
                                
                            <div class="form-group">
                                <label for="quantity">Quantity:</label>
                                <input type="number"  value="" class="form-control" id="quantity" name="quantity"  placeholder="Enter Quantity">
                            </div>
                            
                        <input type="number"  value="<?= $ditems['catelog_id']; ?>" class="form-control" id="cat_id" name="cat_id"  placeholder="<?= $ditems['catelog_id']; ?>" hidden>
                            
                        <div class="form-group">
                                <button type="button" id="add_cart" class="btn" onClick="sendToCart();">Add To Cart</button>
                        </div>  
                                
                        <?php echo form_close(); ?>
                            </div>
                        </div>
                    </div>
                </div>
                    <? } ?>
                    <? } ?>
                </div>
            </div>
            <? } ?>
        </div>
        <!-- /.tab-content -->
    </div><!-- /.card-body -->
</div>
    <!-- /.nav-tabs-custom -->

and this is the script im sending it to:

 <?php 
  $url =  base_url().'donation/add_cart_item'; 
  ?>
  
 <script>
 
    function sendToCart(){

    var catId = $("#cat_id").val();
    var qty = $("#quantity").val();


    $.ajax({
    type: "POST",
    url: "<?php echo $url ?>",
    data: { '<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>', cat_id: catId, quantity: qty, ajax: '1' },
    dataType: "json",
    cache:false,
    success: function() {
    location.reload();
    alert("success");   
    },
    error:function() {
    alert("failure");
    }
    });

    return false; // Stop the browser of loading the page
    }
    
 </script>

and the controller :

public function add_cart_item(){

        $id = $this->input->post('cat_id');
        $qty = $this->input->post('quantity');

        $item = $this->cart_model->get_item($id);
                        
        $data = array(
                'id'      => $id,
                'qty'     => $qty,
                'price'   => $item['price'],
                'name'    => $item['item_name']
                        );

        $data = $this->security->xss_clean($data);
        
        
        $insert = $this->cart->insert($data);

        if ($insert) {
            if ($this->input->post('ajax') != '1') {
                redirect('store'); // If javascript is not enabled, reload the page with new data
            } else {
                echo 'true'; // If javascript is enabled, return true, so the cart gets updated
            }
        } else {
            $this->session->set_flashdata('warning', 'Could not insert the item to cart. Please try again later or contact an Administrator with this error.');
            return false;
        }

Solution

  • You can pass this inside your sendToCart function where this refer to button which is clicked . Then , use .closest() & .find() method to get required input values and pass same to your ajax call . Also , i have added class for quantity and cat_id add that in your html as well.

    Demo Code :

    function sendToCart(el) {
      //get closest outer div ( tabp pane ) ->find inputs with class
      var catId = $(el).closest(".tab-pane").find(".cat_id").val();
      var qty = $(el).closest(".tab-pane").find(".quantity").val();
      console.log("ID = " + catId + " Q = " + qty)
      //your ajax call..
    }
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <div class="card">
      <div class="card-header p-2">
        <ul class="nav nav-pills">
    
          <li class="nav-item">
            <a class="nav-link" href="#A" data-toggle="tab">A</a></li>
    
          <li class="nav-item">
            <a class="nav-link" href="#B" data-toggle="tab">B</a></li>
        </ul>
      </div>
      <div class="card-body">
        <div class="tab-content">
          <div class="tab-pane" id="A">
            <div class="row">
              <div class="col-lg-3 col-6">
                <div class="flip-card">
                  <div class="flip-card-inner">
                    <div class="flip-card-front">
                      <img src="<?= base_url() ?>assets/itemdb/<?= $ditems['image']; ?>" alt="Image" style="width:200px;height:160px;">
                      <h3>
                        Oil
                      </h3>
                    </div>
                    <div class="flip-card-back">
                      <p><b>Price : $134</b></p>
                      <p>
                        <p>Quantity : x 77
                        </p>
                        Soemthinhs ....
                      </p>
    
    
                      <div class="form-group">
                        <label for="quantity">Quantity:</label>
                        <!--use class here-->
                        <input type="number" value="" class="form-control quantity" name="quantity" placeholder="Enter Quantity">
                      </div>
                      <!--use class here-->
                      <input type="number" value="1" class="form-control cat_id" name="cat_id" placeholder="1" hidden>
    
                      <div class="form-group">
                        <!--pass this inside fn which refer to this button-->
                        <button type="button" id="add_cart" class="btn" onClick="sendToCart(this);">Add To Cart</button>
                      </div>
    
                    </div>
                  </div>
                </div>
              </div>
    
            </div>
          </div>
          <div class="tab-pane" id="B">
            <div class="row">
              <div class="col-lg-3 col-6">
                <div class="flip-card">
                  <div class="flip-card-inner">
                    <div class="flip-card-front">
                      <img src="<?= base_url() ?>assets/itemdb/<?= $ditems['image']; ?>" alt="Image" style="width:200px;height:160px;">
                      <h3>
                        Vegeatbles
                      </h3>
                    </div>
                    <div class="flip-card-back">
                      <p><b>Price : $14</b></p>
                      <p>
                        <p>Quantity : 7
                        </p>
                        Soemthinhs .... Soemthinhs ....
                      </p>
    
    
                      <div class="form-group">
                        <label for="quantity">Quantity:</label>
                        <!--use class here-->
                        <input type="number" value="" class="form-control quantity" name="quantity" placeholder="Enter Quantity">
                      </div>
                      <!--use class here-->
                      <input type="number" value="2" class="form-control cat_id" name="cat_id" placeholder="2" hidden>
    
                      <div class="form-group">
                        <!--pass this inside fn which refer to this button-->
                        <button type="button" id="add_cart" class="btn" onClick="sendToCart(this);">Add To Cart</button>
                      </div>
    
                    </div>
                  </div>
                </div>
              </div>
    
            </div>
          </div>
    
        </div>