Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Team

There is an issue on my cart, the problem is when i add 1 item the cart holds to have 2 item instead of 1. How can i resolve this issue?

What I have tried:

HTML
<pre><!-- Displaying Products Start -->
  <div class="container">
    <div id="message"></div>
    <div class="row mt-2 pb-3">
		<?php
    include 'dbconn.php';
    $stmt = $conn->prepare('SELECT * FROM products');
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $row):
        // Access the data using $row['column_name']
        $productID = $row['id'];
        $productName = $row['product_name'];
        // ...
?>
      <div class="col-sm-6 col-md-4 col-lg-3 mb-2">
        <div class="card-deck">
          <div class="card p-2 border-secondary mb-2">
            <img src="<?= $row['product_image'] ?>" class="card-img-top" height="250">
            <div class="card-body p-1">
              <h4 class="card-title text-center text-info"><?= $row['product_name'] ?></h4>
              <h5 class="card-text text-center text-danger">  <?= number_format($row['product_price'],2) ?>/-</h5>

            </div>
            <div class="card-footer p-1">
              <form action="" class="form-submit">
                <div class="row p-2">
                  <div class="col-md-6 py-1 pl-4">
                    Quantity : 
                  </div>
                  <div class="col-md-6">
                    <input type="number" class="form-control pqty" value="<?= $row['product_qty'] ?>">
                  </div>
                </div>
                <input type="hidden" class="pid" value="<?= $row['id'] ?>">
                <input type="hidden" class="pname" value="<?= $row['product_name'] ?>">
                <input type="hidden" class="pprice" value="<?= $row['product_price'] ?>">
                <input type="hidden" class="pimage" value="<?= $row['product_image'] ?>">
                <input type="hidden" class="pcode" value="<?= $row['product_code'] ?>">
                <button class="btn btn-info btn-block addItemBtn">  Add to
                  cart</button>
              </form>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <!-- Displaying Products End -->


JavaScript
// jquery code
<pre lang="Javascript"><pre>$(document).ready(function() {

    // Send product details in the server
    $(".addItemBtn").click(function(e) {
      e.preventDefault();
      var $form = $(this).closest(".form-submit");
      var pid = $form.find(".pid").val();
      var pname = $form.find(".pname").val();
      var pprice = $form.find(".pprice").val();
      var pimage = $form.find(".pimage").val();
      var pcode = $form.find(".pcode").val();

      var pqty = $form.find(".pqty").val();
	  var pqty = 1;

      $.ajax({
        url: 'action.php',
        method: 'post',
        data: {
          pid: pid,
          pname: pname,
          pprice: pprice,
          pqty: pqty,
          pimage: pimage,
          pcode: pcode
        },
        success: function(response) {
          $("#message").html(response);
          window.scrollTo(0, 0);
          load_cart_item_number();
        }
      });
    });

    // Load total no.of items added in the cart and display in the navbar
    load_cart_item_number();

    function load_cart_item_number() {
      $.ajax({
        url: 'action.php',
        method: 'get',
        data: {
          cartItem: "cart_item"
        },
        success: function(response) {
          $("#cart-item").html(response);
        }
      });
    }
  });
  </script>


// action.php
<?php
	session_start();
	require 'dbconn.php';

	// Add products into the cart table
	if (isset($_POST['pid'])) {
	  $pid = $_POST['pid'];
	  $pname = $_POST['pname'];
	  $pprice = $_POST['pprice'];
	  $pimage = $_POST['pimage'];
	  $pcode = $_POST['pcode'];
	  $pqty = $_POST['pqty'];
	  $total_price = $pprice * $pqty;

		$stmt = $conn->prepare('SELECT product_code FROM cart WHERE product_code=:pcode');
		$stmt->bindParam(':pcode', $pcode);
		$stmt->execute();
		$res = $stmt->fetch(PDO::FETCH_ASSOC);
		$code = $res['product_code'] ?? '';


	  if (!$code) {
	    $query = $conn->prepare('INSERT INTO cart (product_name, product_price, product_image, qty, total_price, product_code) VALUES (:pname, :pprice, :pimage, :pqty, :total_price, :pcode)');
		$query->execute([
		'pname' => $pname,
		'pprice' => $pprice,
		'pimage' => $pimage,
		'pqty' => $pqty,
		'total_price' => $total_price,
		'pcode' => $pcode
		]);
	    $query->execute();

	    echo '<div class="alert alert-success alert-dismissible mt-2">
						  <button type="button" class="close" data-dismiss="alert">×</button>
						  Item added to your cart!
						</div>';
	  } else {
	    echo '<div class="alert alert-danger alert-dismissible mt-2">
						  <button type="button" class="close" data-dismiss="alert">×</button>
						  Item already added to your cart!
						</div>';
	  }
	}

	// Get no.of items available in the cart table
	if (isset($_GET['cartItem']) && isset($_GET['cartItem']) == 'cart_item') {
		 $stmt = $conn->prepare('SELECT COUNT(*) as count FROM cart');
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$rows = $result['count'];

    echo $rows;
	}

	// Remove single items from cart
	if (isset($_GET['remove'])) {
	  $id = $_GET['remove'];

		$stmt = $conn->prepare('DELETE FROM cart WHERE id = :id');
		$stmt->execute(['id' => $id]);

	if ($stmt->rowCount() > 0) {
    $_SESSION['showAlert'] = 'block';
    $_SESSION['message'] = 'Item removed from the cart!';
    header('location: cart.php');	
	} else {
    echo 'No item found in the cart with the specified ID.';
	}

	  $stmt->execute();

	  $_SESSION['showAlert'] = 'block';
	  $_SESSION['message'] = 'Item removed from the cart!';
	  header('location:cart.php');
	}

	// Remove all items at once from cart
	if (isset($_GET['clear'])) {
	  $stmt = $conn->prepare('DELETE FROM cart');
	  $stmt->execute();
	  $_SESSION['showAlert'] = 'block';
	  $_SESSION['message'] = 'All Item removed from the cart!';
	  header('location:cart.php');
	}

	// Set total price of the product in the cart table
	if (isset($_POST['qty'])) {
	  $qty = $_POST['qty'];
	  $pid = $_POST['pid'];
	  $pprice = $_POST['pprice'];

	  $tprice = $qty * $pprice;

	  $stmt = $conn->prepare('UPDATE cart SET qty=?, total_price=? WHERE id=?');
	  $stmt->bind_param('isi',$qty,$tprice,$pid);
	  $stmt->execute();
	}

	// Checkout and save customer info in the orders table
	if (isset($_POST['action']) && isset($_POST['action']) == 'order') {
		$name = $_POST['name'];
		$email = $_POST['email'];
		$phone = $_POST['phone'];
		$address = $_POST['address'];
		$pmode = $_POST['pmode'];
		$products = $_POST['products'];
		$grand_total = $_POST['grand_total'];

		$sql = "INSERT INTO orders (name, email, phone, address, payment_method, products, grand_total) VALUES (:fullname, :email, :phone, :address, :payment_method, :products, :grand_total)";
		$stmt = $conn->prepare($sql);

	$stmt->bindValue(':fullname', $name);
	$stmt->bindValue(':email', $email);
	$stmt->bindValue(':phone', $phone);
	$stmt->bindValue(':address', $address);
	$stmt->bindValue(':payment_method', $pmode);
	$stmt->bindValue(':products', $products);
	$stmt->bindValue(':grand_total', $grand_total);

	$stmt->execute();
	
	echo "Checkout information has been stored.";
	  $stmt->execute();
	  $stmt2 = $conn->prepare('DELETE FROM cart');
	  $stmt2->execute();
	  $data .= '<div class="text-center">
								<h1 class="display-4 mt-2 text-danger">Thank You!</h1>
								<h2 class="text-success">Your Order Placed Successfully!</h2>
								<h4 class="bg-danger text-light rounded p-2">Items Purchased : ' . $products . '</h4>
								<h4>Your Name : ' . $name . '</h4>
								<h4>Your E-mail : ' . $email . '</h4>
								<h4>Your Phone : ' . $phone . '</h4>
								<h4>Total Amount Paid : ' . number_format($grand_total,2) . '</h4>
								<h4>Payment Mode : ' . $pmode . '</h4>
						  </div>';
	  echo $data;
	}
?>
Posted
Updated 19-May-23 1:21am
v2
Comments
Member 15627495 18-May-23 14:32pm    
the following declaration have to be out of the current scopr for $.(document).ready()

function load_cart_item_number() {
      $.ajax({
        url: 'action.php',
        method: 'get',
        data: {
          cartItem: "cart_item"
        },
        success: function(response) {
          $("#cart-item").html(response);
        }
      });

// when you click, you operate it a second time ...
Gcobani Mkontwana 19-May-23 4:25am    
@Member 15627495 i dont think that is a right approach to solve the problem, let me share server side to understand why ajax call is there for that reason, i tried to comment it out. Nothing was added to the cart, so the function is there for that reason by calling action.php to do the algorithm. Let me update the code for server side so can have a look.
Member 15627495 19-May-23 4:52am    
it's not 'removing or commenting the function' , but to put it in other location, instead of let the function in the $(document).ready();
You absolutely need this function, it's relevant. but put it out the $(document).ready();

I try to explain why :
when your page is loading then ready(), the function is apply one time ( a query to add an article is sent ),
and the step after, you click the button, and sending an article again. then the cart content appears.

$(document).ready() fires all functions calls in, at end of the page load.

1 solution

You made a call to 'load_cart_item_number' twice which is why you are doubled up on the count...

success: function(response) {
          $("#message").html(response);
          window.scrollTo(0, 0);
          load_cart_item_number(); //CALLED HERE...
        }
      });
    });

    // Load total no.of items added in the cart and display in the navbar
    load_cart_item_number();//CALLED HERE AGAIN...


Personally, I will create a function for it and then call it from there -

public function user_cart( ) {
	//Initiate variables...
	$cart_data_table = "cart";
	
	//You should add some WHERE criteria otherwise all cart items will be returned (maybe where item is not sold etc)...
		$total_in_cart	=	 $this->db_parts->get_results("
			SELECT count(*) as count FROM ".$cart_data_table.""
		);

		return  $total_in_cart[0]->count;
}


Now in your cart page call it -
<button id="check_Cart_Value">
									<span>
										class="fab fa-opencart">
										My Cart										
									</span>
                                    
										<?php 
                                        $cart_count = $get_cart_data->user_cart(); //$get_cart_data is in a class file I created, this should help you though.
                                        echo $cart_count;
                                        ?>
										
								</button>


In my class file -
class Get_cart_Data {
    public function __construct() {
        global $db;

        $this->db_cart = $db;
    }

public function user_cart( ) {
	//Initiate variables...
	$cart_data_table = "cart";
	
	//You should add some WHERE criteria otherwise all cart items will be returned (maybe where item is not sold etc)...
		$total_in_cart	=	 $this->db_parts->get_results("
			SELECT count(*) as count FROM ".$cart_data_table.""
		);

		return  $total_in_cart[0]->count;
}

$get_cart_data = new Get_cart_Data;
 
Share this answer
 
v2
Comments
Gcobani Mkontwana 19-May-23 7:53am    
@Andre Oosthuizen i think i follow your logic now, must first remove that file and create a class will have a unique function, then this function will call on the button from the add to cart, to initiate the cart item being added once?
Andre Oosthuizen 19-May-23 8:15am    
Correct logic yes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900