简体   繁体   中英

Add to cart with ajax in codeigniter

I'm trying add to cart using CodeIgniter and it is working fine but, when I want to do the same through ajax its getting some problem. Can you please look at my codes and tell me where do I get some mistakes? I'm confused how to use ajax to call the add function of the controller . What should I add or do in the ajax code to make this function work?

    <html>
    <head>
    <title>Codeigniter cart class</title>
    <link rel="stylesheet"           href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">

    <script type="text/javascript">
        $(document).ready(function() {
        $("#myform").submit(function(event) {
        event.preventDefault();

        var insert_data= $("#myform").serializeArray();
        $.ajax({
        url:  "<?php echo base_url(); ?>" + "index.php/shopping/add",   
        type: "POST",
        data: insert_data,

            success: function(response) 
            {
                if (response)
                {   

                    //window.location.replace("http://127.0.0.1/codeigniter_cart2/index.php/shopping");
                              window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
                }

                else{
                    alert('sorry');
                }
            }
                });

});
        });
    </script>
</head>
<body>


  <div id='content'>
    <div class="row"> 

    <div class="col-sm-5">
    <h2 align="center">Items</h2>
    <?php


     ?>

    <table id="table" border="0" cellpadding="5px" cellspacing="1px">

        <?php
        foreach ($products as $product) {
            $id = $product['serial'];
            $name = $product['name'];

            $price = $product['price'];
            ?>


                  <tr class="well">
                 <td style="padding-left:15px;"><?php echo $name; ?></td>

                    <td>
                        Rs. <?php echo $price; ?></td>
                    <?php
                    ?>

                    <?php
                    echo form_open('',array('id' => 'myform'));
                    echo form_hidden('id', $id);
                    echo form_hidden('name', $name);
                    echo form_hidden('price', $price);
                    ?> <!--</div>--> 

                    <?php
                    $btn = array(
                        'class' => 'fg-button teal',
                        'value' => 'Add',
                        'name' => 'action',
                        'id' => 'add_button'
                    );
                    ?>
                   <td>
                    <?php
                    // Submit Button.
                    echo form_submit($btn);
                    echo form_close();
                    ?>
                </td>
                </tr>
                <?php } ?>
                </table>

                </div>

    <div class="col-sm-7">
   <!-- <div id="cart" >-->

            <h2 align="center">Items on  Cart</h2>


            <div> 
        <?php  $cart_check = $this->cart->contents();


         if(empty($cart_check)) {
         echo 'To add products to your shopping cart click on "Add" Button'; 
         }  ?> </div>

            <table id="table" border="0" cellpadding="5px" cellspacing="1px">
              <?php
              // All values of cart store in "$cart". 
              if ($cart = $this->cart->contents()): ?>
                <tr id= "main_heading" class="well">

                    <td style="padding-left:15px;"><?>Name</td>
                    <td>Price(Rs)</td>
                    <td>Qty</td>
                    <td>Amount</td>
                    <td>Remove</td>
                </tr>
                <?php
                 // Create form and send all values in "shopping/update_cart" function.
                echo form_open('shopping/update_cart');
                $grand_total = 0;
                $i = 1;

                foreach ($cart as $item):


                    echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
                    echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
                    echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
                    echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
                    echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
                    ?>
                    <tr class="well">

                        <td style="padding-left:15px;">
                  <?php echo $item['name']; ?>
                        </td>
                        <td>
                            <?php echo number_format($item['price'], 2); ?>
                        </td>
                        <td>
                        <?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
                        </td>
                    <?php $grand_total = $grand_total + $item['subtotal']; ?>
                        <td>
                            Rs <?php echo number_format($item['subtotal'], 2) ?>
                        </td>
                        <td>

                        <?php 
                        // cancle image.
                        $path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
                        echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
                        </td>
                 <?php endforeach; ?>
                </tr>
                <tr>
                    <td style="padding-left:30px;"><b>Order Total: Rs <?php 

                    //Grand Total.
                    echo number_format($grand_total, 2); ?></b></td>


                    <td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping/remove/all'">

                        <?php //submit button. ?>
                        <input type="submit" class ='fg-button teal' value="Update Cart">
                        <?php echo form_close(); ?>


                        </td>
                </tr>
<?php endif; ?>
        </table>

        </div>
    <!-- <div id="products_e" align="center">-->
    <!--</div>-->



   <!-- </div>-->
  </div>
  </div>
</body>

Now my controller:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Shopping extends CI_Controller {

    public function __construct()
    {
    parent::__construct();
    //load model
    $this->load->model('billing_model');
            $this->load->library('cart');
}

public function index()
{   

    $data['products'] = $this->billing_model->get_all();

    $this->load->view('shopping_views', $data);
}


 function add()
{

    $insert_data = array(
        'id' => $this->input->post('id'),
        'name' => $this->input->post('name'),
        'price' => $this->input->post('price'),
        'qty' => 1
    );      


    $this->cart->insert($insert_data);


    redirect('shopping');
    return TRUE;
}

    function remove($rowid) {
                // Check rowid value.
    if ($rowid==="all"){
                   // Destroy data which store in  session.
        $this->cart->destroy();
    }else{
                // Destroy selected rowid in session.
        $data = array(
            'rowid'   => $rowid,
            'qty'     => 0
        );
                 // Update cart data, after cancle.
        $this->cart->update($data);
    }

             // This will show cancle data in cart.
    redirect('shopping');
}

    function update_cart(){

            // Recieve post values,calcute them and update
            $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);
    }
    redirect('shopping');        
}   

}

How should I apply this code to ajax? Thanks for the help.

it's not necessary to use "success:"

However if you want to check error or debug

1) press F12 on Browser to open Developer Mode

2) do action (add cart)

3) on tab "Network" find your ajax request and see your error

Modify your add() function as follows:

function add(){
    $insert_data = array('k1' => 'v1', 'k2' => 'v2');      
    $success = $this->cart->insert($insert_data);
    if($success){
        $res = array('status' => 200, 'msg' => 'success', 'somekey' => 'somevalue');
    }else{
        $res = array('status' => 500, 'msg' => 'database err');
    }

    echo json_encode($res);
}

Now the add() function has responded the ajax request with some json-formated data, you can parse the response data in javascript. The (success:) function should be like this:

function(response) {
    if (response){
        var res = JSON.parse(response);
        if(res.status == 200){
            window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
        }else{
            //error handler
            alert(res.msg);
        }
    }else{
        alert('sorry');
    }
});

 function __construct(){ parent::__construct(); $this->load->library(array('session','cart')); $this->load->library(''); $this->load->helper('url'); $this->load->database(); } public function product_list(){ $this->db->select('*'); $this->db->from('product'); $this->db->order_by('product_id','desc'); $rs = $this->db->get(); return $rs->result_array(); } public function product_byId($pid){ $this->db->select('*'); $this->db->from('product'); $this->db->where('product_id',$pid); $rs = $this->db->get(); return $rs->row_array(); } 

Download full code from here http://phpcooker.com/codeigniter-shopping-cart

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM