dwirezkiagung

Heh rekk, selamat datang di postingan pertama blog saya ini. Saya mulai sapaan khas Surabaya saja biar lebih Pribumi #eh. Akhirnya kembali buat blog lagi setelah sekian lama ditinggalkan. Kalau kamu, iya kamu di sini ada yang pernah liat blog namanya zeal-studies itu blog saya dulu hehe. Udah lama ga pernah diurusin dari tahun 2015 mungkin. Blog yang hampir setema dengan yang sekarang ini, masih sama-sama share cerita yang baru didapet pas kuliah, lah blog yang baru ini nih cerita selanjutnya.

Oke sudah ya cerita penyambutan meriahnya, sekarang di sini saya akan share jQuery mycart insert ke database ini adalah salah satu plugin jQuery untuk dipakai di sitem keranjang eCommerce. Dan jQuery mycart ini saya tambahkan ajax untuk proses penyimpanan ke databasenya. Okeh langsung lanjut eksekusi.

Pertama buat database nya dulu ya, misal pakai nama db nya example dan tabelnya tb_transaksi.

CREATE DATABASE example;
CREATE TABLE tb_transaksi (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
total VARCHAR(20) NOT NULL,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Buat script koneksi ke databasenya dengan nama koneksi.php

<?php
class Database{
  private $host = "localhost";
  private $dbname = "example";
  private $user = "root";
  private $password = "";

  private $pdo;
  private $error;
  private $sql;

  public function __construct()
  {
    $dsn = 'mysql:host='.$this->host.';dbname='.$this->dbname;

    $options = [
      PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
      ];
    try{
      $this->pdo = new PDO($dsn, $this->user, $this->password, $options);
      $this->strictMode();

    }catch(PDOException $e){
      //$this->error = $e->getMessage();
      echo 'Koneksi ke server gagal';
      exit;
    }
  }

  private function strictMode()
  {
    $this->pdo->prepare("set session sql_mode='ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER, NO_ENGINE_SUBSTITUTION'")->execute();
  }

  private function run($query, $bindings = [], $type, $fetchMode = null)
  {
    $this->sql = $this->pdo->prepare(trim($query));
    $this->sql->execute($bindings);

    if($type == 'select'){
      return $this->sql->fetchAll($fetchMode);
    }else{
      return $this->sql->rowCount();
    }
  }

  /**
   *  Execute query for insert, update, delete
   *
   *  @param string	$query 		Syntax query
   *  @param array	$bindings	Binding data
   *
   *  @return mixed
   */
  public function execute($query, $bindings = [])
  {
    return $this->run($query, $bindings, 'execute');
  }
}
?>

Lalu buat file index.php nya seperti berikut.

<?php require 'koneksi.php'; ?>
<html>
<head>
  <title>My Cart</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <style>
  .badge-notify{
    background:red;
    position:relative;
    top: -20px;
    right: 10px;
  }
  .my-cart-icon-affix {
    position: fixed;
    z-index: 999;
  }
  </style>
</head>

<body class="container">

  <div class="page-header">
    <h1>Products
      <div style="float: right; cursor: pointer;">
        <span class="glyphicon glyphicon-shopping-cart my-cart-icon"><span class="badge badge-notify my-cart-badge"></span></span>
      </div>
    </h1>
  </div>

  <button type="addNewProduct" name="addNewProduct" id="addNewProduct">Add New Product</button>

  <div class="row">
    <?php
    //$peeeeee = $dbh->query($sql);
    //foreach ($users as $row) {
    ?>
    <div class="col-md-3 text-center">
      <img src="images/img_1.png" width="150px" height="150px">
      <br>
      product 1 - <strong>$10</strong>
      <br>
      <button class="btn btn-danger my-cart-btn" data-id="1" data-name="product 1" data-summary="summary 1" data-price="10" data-quantity="1" data-image="images/img_1.png">Add to Cart</button>
      <a href="#" class="btn btn-info">Details</a>
    </div>

    <div class="col-md-3 text-center">
      <img src="images/img_2.png" width="150px" height="150px">
      <br>
      product 2 - <strong>$20</strong>
      <br>
      <button class="btn btn-danger my-cart-btn" data-id="2" data-name="product 2" data-summary="summary 2" data-price="20" data-quantity="1" data-image="images/img_2.png">Add to Cart</button>
      <a href="#" class="btn btn-info">Details</a>
    </div>

    <div class="col-md-3 text-center">
      <img src="images/img_3.png" width="150px" height="150px">
      <br>
      product 3 - <strong>$30</strong>
      <br>
      <button class="btn btn-danger my-cart-btn" data-id="3" data-name="product 3" data-summary="summary 3" data-price="30" data-quantity="1" data-image="images/img_3.png">Add to Cart</button>
      <a href="#" class="btn btn-info">Details</a>
    </div>

    <div class="col-md-3 text-center">
      <img src="images/img_4.png" width="150px" height="150px">
      <br>
      product 4 - <strong>$40</strong>
      <br>
      <button class="btn btn-danger my-cart-btn" data-id="4" data-name="product 4" data-summary="summary 4" data-price="40" data-quantity="1" data-image="images/img_4.png">Add to Cart</button>
      <a href="#" class="btn btn-info">Details</a>
    </div>

    <div class="col-md-3 text-center">
      <img src="images/img_5.png" width="150px" height="150px">
      <br>
      product 5 - <strong>$50</strong>
      <br>
      <button class="btn btn-danger my-cart-btn" data-id="5" data-name="product 5" data-summary="summary 5" data-price="50" data-quantity="1" data-image="images/img_5.png">Add to Cart</button>
      <a href="#" class="btn btn-info">Details</a>
    </div>

  </div>


  <script src="js/jquery-2.2.3.min.js"></script>
  <script type='text/javascript' src="js/bootstrap.min.js"></script>
  <script type='text/javascript' src="js/jquery.mycart.js"></script>
  <script type="text/javascript">
  $(function () {

    var goToCartIcon = function($addTocartBtn){
      var $cartIcon = $(".my-cart-icon");
      var $image = $('<img width="30px" height="30px" src="' + $addTocartBtn.data("image") + '"/>').css({"position": "fixed", "z-index": "999"});
      $addTocartBtn.prepend($image);
      var position = $cartIcon.position();
      $image.animate({
        top: position.top,
        left: position.left
      }, 500 , "linear", function() {
        $image.remove();
      });
    }

    $('.my-cart-btn').myCart({
      currencySymbol: '$',
      classCartIcon: 'my-cart-icon',
      classCartBadge: 'my-cart-badge',
      classProductQuantity: 'my-product-quantity',
      classProductRemove: 'my-product-remove',
      classCheckoutCart: 'my-cart-checkout',
      affixCartIcon: true,
      showCheckoutModal: true,
      numberOfDecimals: 2,
      clickOnAddToCart: function($addTocart){
        goToCartIcon($addTocart);
      },
      afterAddOnCart: function(products, totalPrice, totalQuantity) {
        console.log("afterAddOnCart", products, totalPrice, totalQuantity);
      },
      clickOnCartIcon: function($cartIcon, products, totalPrice, totalQuantity) {
        console.log("cart icon clicked", $cartIcon, products, totalPrice, totalQuantity);
      },
      checkoutCart: function(products, totalPrice, totalQuantity) {
        $.ajax({
          url: "save.php",
          type: "POST",
          data: $('#formOrder').serialize(),
          dataType: "JSON",
          success: function(data){
            alert('Data has been inserted');
            //console.log(data);
          }
        });
      }
      /*getDiscountPrice: function(products, totalPrice, totalQuantity) {
        console.log("calculating discount", products, totalPrice, totalQuantity);
        return totalPrice * 0.5;
      }*/
    });

    $("#addNewProduct").click(function(event) {
      var currentElementNo = $(".row").children().length + 1;
      $(".row").append('<div class="col-md-3 text-center"><img src="images/img_empty.png" width="150px" height="150px"><br>product ' + currentElementNo + ' - <strong>Rp' + currentElementNo + '</strong><br><button class="btn btn-danger my-cart-btn" data-id="' + currentElementNo + '" data-name="product ' + currentElementNo + '" data-summary="summary ' + currentElementNo + '" data-price="' + currentElementNo + '" data-quantity="1" data-image="images/img_empty.png">Add to Cart</button><a href="#" class="btn btn-info">Details</a></div>')
    });
  });
  </script>

</body>

</html>

File index.php ini adalah default awal saat saya download plugin mycart, saya tambahkan ajax untuk mendapatkan data dan mengarahkannya ke proses penyimpanannya yaitu save.php. Sudah saya tandai merah penambahan ajax mulai pada line 123.

Jangan lupa tambahkan tag <form>pada file jquery.mycart.js, di dalam folder js. Tambahannya seperti berikut.

$('body').append(
 '<form action="" id="formOrder" role="form" method="POST">' +
 '<div class="modal fade" id="' + idCartModal + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">' +
 '<div class="modal-dialog" role="document">' +
 '<div class="modal-content">' +
 '<div class="modal-header">' +
 '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
 '<h4 class="modal-title" id="myModalLabel"><span class="glyphicon glyphicon-shopping-cart"></span> My Cart</h4>' +
 '</div>' +
 '<div class="modal-body">' +
 '<table class="table table-hover table-responsive" id="' + idCartTable + '"></table>' +
 '</div>' +
 '<div class="modal-footer">' +
 '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
 '<button type="button" class="btn btn-primary ' + classCheckoutCart + '">Checkout</button>' +
 '</div>' +
 '</div>' +
 '</div>' +
 '</div>' +
 '</div>' +
 '</form>'
 );

Penambahan <form> hanya pada append ‘body’, karena di bagian bawah hanya perhitungan quantity dan total.

Saya lampirkan projek mentahnya siapa tau ada teman-teman yang ingin mengembangkan atau menyelesaikan beberapa tugas, file bisa diunduh di bawah ini.

Download

Oke selesai deh, ini juga jadi catatan saya jika mungkin nanti saya ada lupanya. Yup sekian, semoga dapat membantu teman-teman sekalian ya.

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *