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