繁体   English   中英

添加到购物车与Codeigniter中的Ajax

[英]Add to cart with ajax in codeigniter

我正在尝试使用CodeIgniter添加到购物车,并且工作正常,但是,当我想通过ajax进行相同操作时,出现了一些问题。 您能看一下我的密码并告诉我在哪里出错吗? 我很困惑如何使用ajax调用控制器的add函数。 我应该在ajax代码中添加或执行哪些操作才能使此功能正常工作?

    <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>

现在我的控制器:

<?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');        
}   

}

我应该如何将此代码应用于ajax? 谢谢您的帮助。

不必使用“成功”:

但是,如果您要检查错误或调试

1)在浏览器上按F12打开开发人员模式

2)做动作(加入购物车)

3)在“网络”标签上,找到您的Ajax请求并查看您的错误

修改您的add()函数,如下所示:

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);
}

现在add()函数已经用一些json格式的数据响应了ajax请求,您可以使用javascript解析响应数据。 (success :)函数应如下所示:

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(); } 

从此处下载完整代码http://phpcooker.com/codeigniter-shopping-cart

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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