0

Describing the problem in short :

CLICK on the image QTY buttons up and down

QTY buttons worked for simple quantity increase, before it was added an ajax part of complexity to increase the subtotal value of items already in cart, now this is where buttons stopped working and also not parsing the data to start increasing quantity of a particular product, which also then adds to the already calculated subtotal value of the products in cart.

I tried searching for some other solutions, but i just don't have enough experience yet to try to mix them in. But i did check dev tools in Firefox and Chrome and i currently didn't have any errors showing. I tried few fixes and eliminated all the possible errors, but i can't figure out the problem.

I am guessing there could be problem in which order the syntax is written or nested, i presume or i am completely wrong.

I watched the stack-overflow for many years but i never tried more complex projects, but now i decided i want to be in the programming field and so i want to participate more personally as well.

Hopefully someone can help with this weird situation. <3

This is working version i have left this let statements and prepared statement for price increase if anyone can properly connect the logic here. I DID REMOVE AJAX HERE => Buttons are now working up and down, but obviously not affecting changes in cart subtotal price.

  /* NOTE PRODUCT QTY UP AND DOWN */
  let $qty_up = $(".qty .qty-up");
  let $qty_down = $(".qty .qty-down");
  let $deal_price = ("#deal-price");
  //let $input = $(".qty .qty_input");

  /* NOTE CLICK ON QTY UP BUTTON */
  $qty_up.click(function (e) {

    let $input = $(`.qty_input[data-id='${$(this).data("id")}']`);
    let $price = $(`.product_price[data-id='${$(this).data("id")}']`);
    

          if ($input.val() >= 1 && $input.val() <= 9) {
            $input.val(function (i, oldval) {
              return ++oldval;
            });
          
            // NOTE INCREASE THE PRICE OF THE PRODUCT
            $price.text(parseInt(item_price * $input.val()).toFixed(2));

            // NOTE SET SUBTOTAL PRICE
            let subtotal = parseInt($deal_price.text()) + parseInt(item_price);
            $deal_price.text(subtotal.toFixed(2));
          
          }  
  });

  /* NOTE CLICK ON QTY DOWN BUTTON */
  $qty_down.click(function (e) {

    let $input = $(`.qty_input[data-id='${$(this).data("id")}']`);
    let $price = $(`.product_price[data-id='${$(this).data("id")}']`);

          if ($input.val() > 1 && $input.val() <= 10) {
            $input.val(function (i, oldval) {
              return --oldval;
            });
          
            // NOTE INCREASE THE PRICE OF THE PRODUCT
            $price.text(parseInt(item_price * $input.val()).toFixed(2));

            // NOTE SET SUBTOTAL PRICE
            let subtotal = parseInt($deal_price.text()) - parseInt(item_price);
            $deal_price.text(subtotal.toFixed(2));
          
          }

  });

Full index.js script, because it has direct correlation with Owl Carousel plugin. So here it is : THIS IS NON WORKING VERSION FOR BUTTONS UP AND DOWN ON CLICK WITH AJAX(JQuery)!

// NOTE OWL CAROUSEL DOCUMENT READY

$(document).ready(function () {

  /* BANNER OWL 2 CAROUSEL */
  $("#banner-area .owl-carousel").owlCarousel({
    dots: true,
    items: 1,
  });

  /* NOTE TOP SALE OWL 2 CAROUSEL */
  $("#top-sale .owl-carousel").owlCarousel({
    loop: true,
    nav: true,
    dots: false,
    responsive: {
      0: {
        items: 1,
      },
      600: {
        items: 3,
      },
      1000: {
        items: 5,
      },
    },
  });

  /* NOTE ISOTOPE FILTER */
  var $grid = $(".grid").isotope({
    itemSelector: ".grid-item",
    layoutMode: "fitRows",
  });

  /* NOTE FILTER ITEMS ON BUTTON CLICK */
  $(".button-group").on("click", "button", function () {
    var filterValue = $(this).attr("data-filter");
    $grid.isotope({ filter: filterValue });
  });

  /* NOTE NEW PHONES OWL CAROUSEL */
  $("#new-phones .owl-carousel").owlCarousel({
    loop: true,
    nav: false,
    dots: true,
    responsive: {
      0: {
        items: 1,
      },
      600: {
        items: 3,
      },
      1000: {
        items: 5,
      },
    },
  });

  /* NOTE LATEST BLOGS ON UPCOMING NEW TECH OWL CAROUSEL */
  $("#blogs .owl-carousel").owlCarousel({
    loop: true,
    nav: false,
    dots: true,
    responsive: {
      0: {
        items: 1,
      },
      600: {
        items: 3,
      },
    },
  });

  /* NOTE PRODUCT QTY UP AND DOWN */
  let $qty_up = $(".qty .qty-up");
  let $qty_down = $(".qty .qty-down");
  let $deal_price = ("#deal-price");
  //let $input = $(".qty .qty_input");

  /* NOTE CLICK ON QTY UP BUTTON */
  $qty_up.click(function (e) {

    let $input = $(`.qty_input[data-id='${$(this).data("id")}']`);
    let $price = $(`.product_price[data-id='${$(this).data("id")}']`);

    // NOTE CHANGE PRODUCT PRICE USING AJAX CALL
    $.ajax({
      url: "./Template/ajax.php", type: 'post', data:
        { itemid: $(this).data("id") }, dataType: 'json', success: function (result) {
          let obj = JSON.parse(result);
          let item_price = obj[0]['item_price'];

          if ($input.val() >= 1 && $input.val() <= 9) {
            $input.val(function (i, oldval) {
              return ++oldval;
            });
          
            // NOTE INCREASE THE PRICE OF THE PRODUCT
            $price.text(parseInt(item_price * $input.val()).toFixed(2));

            // NOTE SET SUBTOTAL PRICE
            let subtotal = parseInt($deal_price.text()) + parseInt(item_price);
            $deal_price.text(subtotal.toFixed(2));
          
          }

        }
    }); // NOTE CLOSING AJAX REQUEST
  });

  /* NOTE CLICK ON QTY DOWN BUTTON */
  $qty_down.click(function (e) {

    let $input = $(`.qty_input[data-id='${$(this).data("id")}']`);
    let $price = $(`.product_price[data-id='${$(this).data("id")}']`);

    // NOTE CHANGE PRODUCT PRICE USING AJAX CALL
    $.ajax({
      url: "./Template/ajax.php", type: 'post', data:
        { itemid: $(this).data("id") }, dataType: 'json', success: function (result) {
          let obj = JSON.parse(result);
          let item_price = obj[0]['item_price'];

          if ($input.val() > 1 && $input.val() <= 10) {
            $input.val(function (i, oldval) {
              return --oldval;
            });
          
            // NOTE INCREASE THE PRICE OF THE PRODUCT
            $price.text(parseInt(item_price * $input.val()).toFixed(2));

            // NOTE SET SUBTOTAL PRICE
            let subtotal = parseInt($deal_price.text()) - parseInt(item_price);
            $deal_price.text(subtotal.toFixed(2));
          
          }

        }
    }); // NOTE CLOSING AJAX REQUEST
  });


});

_cart-template.php EXTENSION PHP FILE to main cart.php

<!-- NOTE SHOPPING_CART SECTION -->
<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete-cart-submit'])) {
        $deletedRecord = $Cart->deleteCart($_POST['item_id']);
    }
}

?>

<section id="cart" class="py-3 mb-5">
    <div class="container-fluid w-75">
        <h5 class="font-roboto font-size-20">Košarica</h5>

        <!-- NOTE SHOPPING CART ITEMS -->
        <div class="row">
            <div class="col-sm-9">
                <?php
                foreach ($product->getData('cart') as $item) :
                    $cart = $product->getProduct($item['item_id']);
                    $subTotal[] = array_map(function ($item) {
                ?>
                        <!-- NOTE CART ITEM -->
                        <div class="row border-top py-3 mt-3">
                            <div class="col-sm-2">
                                <img src="<?php echo $item['item_image'] ?? "./assets/products/1.png" ?>" style="height: 120px;" alt="cart1" class="img-fluid">
                            </div>
                            <div class="col-sm-8">
                                <h5 class="font-roboto font-size-20"><?php echo $item['item_name'] ?? "Unknown"; ?></h5>
                                <small>by <?php echo $item['item_brand'] ?? "Brand"; ?></small>

                                <!-- NOTE PRODUCT RATING -->
                                <div class="d-flex">
                                    <div class="rating text-warning font-size-12">
                                        <span><i class="fas fa-star"></i></span>
                                        <span><i class="fas fa-star"></i></span>
                                        <span><i class="fas fa-star"></i></span>
                                        <span><i class="fas fa-star"></i></span>
                                        <span><i class="far fa-star"></i></span>
                                    </div>
                                    <a href="#" class="px-2 font-rale font-size-14">20,933 ratings</a>
                                </div>
                                <!-- NOTE PRODUCT RATING -->

                                <!-- NOTE PRODUCT QTY -->
                                <div class="qty d-flex pt-2">
                                    <div class="d-flex font-rale w-25">
                                        <button data-id="<?php echo $item['item_id'] ?? '0'; ?>" class="qty-up border bg-light"><i class="fas fa-angle-up"></i>
                                        </button>
                                        <input type="text" data-id="<?php echo $item['item_id'] ?? '0'; ?>" class="qty_input border px-2 w-50 bg-light text-center" disabled value="1" placeholder="1">
                                        <button data-id="<?php echo $item['item_id'] ?? '0'; ?>" class="qty-down border bg-light"><i class="fas fa-angle-down"></i>
                                        </button>
                                    </div>

                                    <form method="post">
                                        <input type="hidden" value="<?php echo $item['item_id'] ?? 0; ?>" name="item_id">
                                        <button type="submit" name="delete-cart-submit" class="btn font-roboto text-danger px-3 border-right">Izbriši</button>
                                    </form>

                                    <button type="submit" class="btn font-roboto text-danger px-3 border-right">Shrani za poznejši nakup</button>
                                </div>
                                <!-- NOTE PRODUCT QTY -->

                            </div>

                            <!-- NOTE PRODUCT PRICE SPAN -->
                            <div class="col-sm-2 text-right">
                                <div class="font-size-20 text-danger font-roboto">
                                    $<span class="product_price" data-id="<?php echo $item['item_id'] ?? '0'; ?>"><?php echo $item['item_price'] ?? 0; ?></span>
                                </div>
                            </div>
                            <!-- NOTE PRODUCT PRICE SPAN -->

                        </div>
                        <!-- NOTE CART ITEM -->
                <?php
                        return $item['item_price'];
                    }, $cart); // NOTE CLOSING ARRAY_MAP FUNCTION
                endforeach;

                ?>
            </div>

            <!-- NOTE SUBTOTAL SECTION -->
            <div class="col-sm-3">
                <div class="sub-total border text-center mt-2">
                    <h6 class="font-size-12 font-rale text-success py-3"><i class="fas fa-check"></i>Vaše naročilo ustreza brezplačni dostavi</h6>
                    <div class="border-top py-4">
                        <h5 class="font-roboto font-size-20">Skupno (<?php echo isset($subTotal) ? count($subTotal) : 0; ?> izdelek/a/i):&nbsp;<span class="text-danger">$<span class="text-danger" id="deal-price"><?php echo isset($subTotal) ? $Cart->getSum($subTotal) : 0; ?></span></span></h5>
                        <button type="submit" class="btn btn-warning mt-3">Nadaljujte z nakupom</button>
                    </div>
                </div>
            </div>
            <!-- NOTE SUBTOTAL SECTION -->

        </div>
        <!-- NOTE SHOPPING CART ITEMS -->
    </div>
</section>
<!-- NOTE SHOPPING_CART SECTION -->

Ajax.php encoding JSON and later calling it in Index.js for QTY UP and DOWN buttons !

<?php

// NOTE REQUIRE MYSQLi CONNECTION
require('../database/DBController.php');

// NOTE REQUIRE PRODUCT CLASS
require('../database/Product.php');

// NOTE DBController OBJECT
$db = new DBController();

// NOTE PRODUCT OBJECT
$product = new Product($db);


if(isset($_POST['item_id'])){
    $result = $product->getProduct($_POST['item_id']);
    echo json_encode($result);
}

?>

Cart.php DATABASE FILE, where i store, insert or delete items from

<?php
ob_start();
// NOTE PHP CART CLASS
class Cart
{
    public $db = null;

    public function __construct(DBController $db)
    {
        if(!isset($db->con)) return null;
        $this->db = $db;
    }

    // NOTE INSERT INTO THE CART TABLE
    public function insertIntoCart($parameter = null, $table = "cart"){
        if ($this->db->con != null){
            if($parameter != null){
                // NOTE "INSERT INTO CART TABLE (user_id) values(0)"
                // GET TABLE COLUMNS
                $columns = implode(',', array_keys($parameter));
                
                $values = implode(',', array_values($parameter));
                

                // NOTE CREATE SQL QUERY
                $query_string = sprintf("INSERT INTO %s(%s) VALUES(%s)", $table, $columns, $values);
                
                // NOTE EXECUTE QUERY
                $result = $this->db->con->query($query_string);
                return $result;
            }
        }
    }

    // NOTE TO GET USER_ID AND ITEM_ID AND INSERT INTO CART TABLE
    public function addToCart($userid, $itemid){
        if(isset($userid) && isset($itemid)){
           $parameter = array(
              "user_id" => $userid,
              "item_id" => $itemid
           );

           // NOTE INSERT DATA INTO CART
          $result = $this->insertIntoCart($parameter);
          if($result){
            header("Location:" .$_SERVER['PHP_SELF']);
          } 
        }
    }

    // NOTE DELETE CART ITEM USING CART ITEM ID
    public function deleteCart($item_id = null, $table = 'cart'){
        if($item_id != null){
        $result = $this->db->con->query("DELETE FROM {$table} WHERE item_id={$item_id}");
        if($result){
            header("Location:" .$_SERVER['PHP_SELF']);
        }
        return $result;
        }
    }

    // NOTE CALCULATING SUBTOTAL VALUE OF THE ITEMS IN THE CART (SUB TOTAL) !
    public function getSum($array){
        if(isset($array)){
            $sum = 0;
            foreach ($array as $item) {
                $sum += floatval($item[0]);
            }
            return sprintf('%.2f', $sum);
        }
    }

    // NOTE GET ITEM_ID OF SHOPPING CART LIST
    public function getCartId($cartArray = null, $key = "item_id"){
        if($cartArray != null){
            $cart_id = array_map(function($value) use($key){
               return $value[$key]; 
            }, $cartArray);
            return $cart_id;
        }
    }
}
?>

cart.php MAIN CART PHP FILE

<?php
ob_start();
// NOTE INCLUDE HEADER.PHP
include('header.php');
?>

<?php

// NOTE INCLUDE _CART-TEMPLATE.PHP
include('Template/_cart-template.php');
// NOTE INCLUDE _CART-TEMPLATE.PHP

// NOTE INCLUDE _NEW-PHONES.PHP
include('Template/_new-phones.php');
// NOTE INCLUDE _NEW-PHONES.PHP

?>

<?php
// NOTE INCLUDE FOOTER.PHP
include('footer.php');
?>
  • 2
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 16 '20 at 20:23
  • Your first snippet is not working properly. Probably you forgot to include a reference to jQuery script. – Sagnalrac Aug 17 '20 at 01:18
  • @Dharman yeah this is just for testing puproses atm. Thank you for reminding me anyway. I will defenetly go through that, what you mentioned. I noted your answer in my TODO list to remind myself. Thank you sir <3. – AlenIdealen Aug 17 '20 at 07:07
  • @Sagnalrac i will try to use refference to JQuery and will report back if it works. – AlenIdealen Aug 17 '20 at 07:16
  • Can someone please enlighten me, where did i go wrong =/. – AlenIdealen Aug 18 '20 at 08:31

0 Answers0