dongpo8702 2016-03-02 07:30
浏览 60

添加到购物车中的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.

  • 写回答

3条回答 默认 最新

  • duanrong5927 2016-03-02 07:43
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c