Add to Cart and Checkout Code in PHP - onlyxcodes

Sunday, 25 October 2020

Add to Cart and Checkout Code in PHP

Hi guys, I'm going to share add to cart and checkout code in PHP today after a long period. In other terms, we create a shopping cart system using PHP & MYSQL.


You've noticed e-commerce websites like Amazon, Flipkart, etc. add to cart functionality. The cart button produces, simply, some stuff that customers want to purchase. The shopping cart enabled you to view the item details with the total price before making an order from the checkout process. And the price of items is full of back-end estimates.


This tutorial can help you a lot, You will be able to create a project for your shopping cart using PHP. I used an extremely $.ajax() method in this tutorial to store, remove and update product quantity values in the cart without refreshing the page, and that all tasks are done by PHP on the back-end side.


If the customers have sent the order, the product details will be entered into the MySQL database. Recognize this tutorial code pretty quickly, and I put short animated videos that look amazing. Using PHP PDO, let's build shopping cart features.


Add to Cart and Checkout Code in PHP

Table Content

1. What is Add to Cart?

2. Technology

3. Project File Structure

4. Database And Table Creating

5. Connect Database

6. Display Items from Database

7. Add to Cart Item

8. Get Total Number of Items In Cart

9. Display Item In Cart

10. Delete Specific Item In Cart

11. Delete All Items In Cart

12. Update Item Quantity In Cart

13. Checkout Item


1. What is Add to Cart?

Add to Cart is a method of adding products to the cart to compose a temporary number of stuff. That will locate the products before you exit our website.


You can export a list of products that are saved in your cart some of which are confident for purchasing and increasing the average things per order.


2. Technology

Front end:


Bootstrap: This front-end bundle is used to design all pages in a responsive and colorful visual format.

jQuery/Ajax: We deliver custom codes using both tactics and execute our project.


Back end :


PHP: In the Back end, we use Hypertext Preprocessor (PHP).

MySQL: In this project, we use the MySQL database.


3. Project File Structure

Check out the file structure of the PHP shopping cart system.

Add-To-Cart-PHP/
├──bootstrap/
	├── css/
	│   ├── bootstrap.min.css
	│   ├── bootstrap.min.css.map
	│   ├── bootstrap-grid.css
	│   ├── bootstrap-grid.css.map
	│   ├── bootstrap-grid.min.css
	│   ├── bootstrap-grid.min.css.map
	├── js/
	│   └── bootstrap.min.js
	│   └── bootstrap.min.js.map
	│   └── bootstrap.bundle.js
	│   └── bootstrap.bundle.js.map
	│   └── bootstrap.bundle.min.js 
	│   └── bootstrap.bundle.min.map 
├──images/
	├── bracelet.png
	├── men-fotware.jpg
	├── scating.jpg
	├── shirt.jpg
	├── sunglass.png
	├── women-fotware.jpg
├──jquery/
	├── jquery.min.js
	├── jquery.min.js.map
	
action.php
cart.php
checkout.php
dbconfig.php
index.php

4. Database And Table Creating

First, build a database called shopping_cart_db because I installed this database name in MySQL. You will have to modify the database name in the PHP file whenever you create a database with a different name. 


You need to create three tables below after installing the database successfully. 


Product Table


Click the database on the shopping_cart_db panel on the left and execute the following SQL code. The product table with six dumping item records will be generated below the SQL code.


CREATE TABLE IF NOT EXISTS `product` (
  `product_id` int(11) NOT NULL,
  `product_name` varchar(100) NOT NULL,
  `product_price` varchar(50) NOT NULL,
  `product_image` varchar(255) NOT NULL,
  `product_code` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

product table

See product table dumping record.


INSERT INTO `product` (`product_id`, `product_name`, `product_price`, `product_image`, `product_code`) VALUES
(1, 'bracelet', '200', 'bracelet.png', 'p1000'),
(2, 'scating', '500', 'scating.jpg', 'p1001'),
(3, 'men-fotware', '250', 'men-fotware.jpg', 'p1002'),
(4, 'sunglass', '100', 'sunglass.png', 'p1003'),
(5, 'shirt', '400', 'shirt.jpg', 'p1004'),
(6, 'women-fotware', '700', 'women-fotware.jpg', 'p1005');

product table dumping record.

Cart Table


Next, to construct a cart table containing the six fields, run the SQL code below.


This table holds all tasks such as adding to the cart button, updating quantity values, removing specific items, and clearing all item values from the cart to the customer.


CREATE TABLE IF NOT EXISTS `cart` (
  `cart_id` int(11) NOT NULL,
  `product_name` varchar(100) NOT NULL,
  `product_price` varchar(50) NOT NULL,
  `product_image` varchar(255) NOT NULL,
  `quantity` int(10) NOT NULL,
  `total_price` varchar(100) NOT NULL,
  `product_code` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

cart table

Order Table


Last, by following the SQL code, you build the order table. Users fill up all their information in the checkout process after we store order details in this table.


CREATE TABLE `orders` (
  `order_id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `address` varchar(255) NOT NULL,
  `payment_mode` varchar(20) NOT NULL,
  `products` varchar(255) NOT NULL,
  `paid_amount` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

orders table

5. Connect Database

In the "dbconfig.php" file, we enter MySQL authentication information using the PDO extension to access database tables, simply wrapping up the following code.


<?php
$db_host="localhost"; 
$db_user="root";	
$db_password="";	
$db_name="shopping_cart_db";	

try
{
	$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
	$e->getMessage();
}

?>

6. Display Items from Database

The "index.php" page is our home page that will be viewed first by our guests. All items from the database are retrieved on this page and presented as a simple online shopping store format.


I list the image, name, and price of the product in three fields. Exactly below the price I put to add to the cart button, users add unique products by clicking this button. And our shopping-cart box will be on the right side of the page, which will keep track of items that users will buy later.


The HTML form is the least important component here. Note the hidden input values? A form with these hidden values is contained in each item.


<div class="row">
		
	<?php
	require_once "dbconfig.php";
	$select_stmt=$db->prepare("SELECT * FROM product");	
	$select_stmt->execute();
	while($row=$select_stmt->fetch(PDO::FETCH_ASSOC))
	{
	?>
		<div class="col-lg-4 col-md-6 mb-4">
            <div class="card h-100">
			<a href="#"><img class="card-img-top" src="images/<?php echo $row['product_image']; ?>" width="400px" height="200px"></a>
			  
            <div class="card-body">
				<h4 class="card-title text-primary"><?php echo $row['product_name']; ?> </h4>
                <h5><?php echo number_format($row['product_price'],2); ?>/-</h5>
            </div>
			  
            <div class="card-footer">
				<form class="form-submit">
					<input type="hidden" class="pid" value="<?php echo $row['product_id']; ?>">
					<input type="hidden" class="pname" value="<?php echo $row['product_name']; ?>">
					<input type="hidden" class="pprice" value="<?php echo $row['product_price']; ?>">
					<input type="hidden" class="pimage" value="<?php echo $row['product_image']; ?>">
					<input type="hidden" class="pcode" value="<?php echo $row['product_code']; ?>">
					<button id="addItem" class="btn btn-success btn-md">Add to Cart</button>
				</form>
            </div>
			  
            </div>
        </div>
	<?php
	}
	?>

</div>

Display Items from Database

7. Add to Cart Item

If the user clicks on the add to cart button, the on() method causes and triggers the event button. The #addItem id attribute of button.


The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. ( according to w3schools ).


In the closest() method, we transfer the form class attribute value .form-submit. Since this parent value is the ancestor of the button and will be stored in a form variable.


The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. ( according to w3schools ).


All hidden input tag class attribute values are transferred here. .pid, .pname, .pprice, .pimage, and .pcode, respectively. And the val() method uses certain class attribute values to get all the values.


$.ajax() is a powerful and quick way to distribute the form values to another page by requesting the PHP back-end file, and here in this project I built the action.php file, with the HTTP POST method, it will peacefully handle the ajax request.


If the item is successfully added or already detected, all messages will be shown under the <div class='alert-message'></div > tag. he alert-message class attribute of division tag.


The scrollTo() method scrolls the document to the specified coordinates. ( according to w3schools ).


Here we pass window.scrollTo(0,0);. Scroll the message to the horizontal '0' and vertical '0' position:


The last function we call is load_cart_item_number(); the next step will be explored.


<script type="text/javascript">
	$(document).ready(function(){ 
		$(document).on("click", "#addItem", function(e){	
			e.preventDefault();
			var form = $(this).closest(".form-submit");
			var id = form.find(".pid").val();
			var name = form.find(".pname").val();
			var price = form.find(".pprice").val();
			var image = form.find(".pimage").val();
			var code = form.find(".pcode").val();
			
			$.ajax({
				url: "action.php",
				method: "post",
				data: {pid:id, pname:name, pprice:price, pimage:image, pcode:code},
				success:function(response){
					$(".alert-message").html(response);
					window.scrollTo(0,0);
					load_cart_item_number();
				} 
			});
		});	
	});
</script>

Add to Cart Code


This is an action.php file with simple PHP and HTML code coupled together. The file works quietly on the back end side. This file accepts all data sent from the $.ajax() method and shows the output of the index.php file without refreshing the page.


If the user clicks on the add to cart button, this code will check whether or not this item is already available in the cart table. If located, send the already added message item, otherwise, insert the new item in the cart table and send the add successfully message.






<?php
session_start();
require_once "dbconfig.php";

if(isset($_POST["pid"]) && isset($_POST["pname"]) && isset($_POST["pprice"]) && isset($_POST["pimage"]) && isset($_POST["pcode"]))
{
	$id	= $_POST["pid"];
	$name 	= $_POST["pname"];
	$price 	= $_POST["pprice"];
	$image 	= $_POST["pimage"];
	$code 	= $_POST["pcode"];
	$qty = 1 ;
	
	$select_stmt=$db->prepare("SELECT product_code FROM cart WHERE product_code=:code");
	$select_stmt->execute(array(":code"=>$code));  
	$row=$select_stmt->fetch(PDO::FETCH_ASSOC);
	
	$check_code = $row["product_code"];
		
	if(!$check_code)
	{
		$insert_stmt=$db->prepare("INSERT INTO cart(product_name,
													product_price,
													product_image, 
													quantity,
													total_price,
													product_code) 
												VALUES
													(:name,
													:price,
													:image,
													:qty,
													:ttl_price,
													:code)"); 					
		$insert_stmt->bindParam(":name",$name);	
		$insert_stmt->bindParam(":price",$price);	
		$insert_stmt->bindParam(":image",$image);	
		$insert_stmt->bindParam(":qty",$qty);	 
		$insert_stmt->bindParam(":ttl_price",$price);	
		$insert_stmt->bindParam(":code",$code);	
		$insert_stmt->execute();
				
		echo '<div class="alert alert-success alert-dismissible mt-2">
				<button type="button" class="close" data-dismiss="alert">×</button>
				<strong>Item added to your cart</strong> 
			  </div>';				
	}
	else
	{
		echo '<div class="alert alert-danger alert-dismissible mt-2">
				<button type="button" class="close" data-dismiss="alert">×</button>
				<strong>Item already added to your cart!</strong> 
			  </div>';
	}
}





Add to Cart Item

8. Get Total Number of Items In Cart

Next, you can see below that the load_cart_item_number() function is created. Within this function, the $.ajax() method sends the request through the HTTP GET method to the action.php file and obtains total item values in the cart table. 


All values display our shopping cart box's top panel on the right side of the page. The #cart-item is the Id attribute for the span tag, showing the total values within this tag.


<script type="text/javascript">
	$(document).ready(function(){ 
		$(document).on("click", "#addItem", function(e){	
			e.preventDefault();
			var form = $(this).closest(".form-submit");
			var id = form.find(".pid").val();
			var name = form.find(".pname").val();
			var price = form.find(".pprice").val();
			var image = form.find(".pimage").val();
			var code = form.find(".pcode").val();
			
			$.ajax({
				url: "action.php",
				method: "post",
				data: {pid:id, pname:name, pprice:price, pimage:image, pcode:code},
				success:function(response){
					$(".alert-message").html(response);
					window.scrollTo(0,0);
					load_cart_item_number();
				} 
			});
		});
		
		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>

Store the source code below in the action.php file and call $.ajax() request via the HTTP GET method. We get the variable 'cartItem' here, and the isset() function sets this variable.


In the prepare() statement, Fire PDO selects a query, and the execute() method invokes the query statement. We return the total number of row record values from the cart table using the rowCount() function.


if(isset($_GET["cartItem"]) && isset($_GET["cartItem"])=="cart_item")
{
	$select_stmt=$db->prepare("SELECT * FROM cart");
	$select_stmt->execute();  
	$row=$select_stmt->rowCount();
	echo $row;
}

Get Total Number of Items In Cart



9. Display Item In Cart

Using bootstrap bundles, the "cart.php" file builds a simple shopping cart. All items available in the cart table are displayed in this file with the total price as well as to keep track of user items.






<div class="container">
	<div class="row">
        <div class="col-12">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th scope="col"> </th>
                            <th scope="col">Product</th>
                            <th scope="col">Price</th>
                            <th scope="col" class="text-center">Quantity</th>
                            <th scope="col" class="text-right">Total Price</th>
                            <th scope="col" class="text-right">
							<a href="action.php?clear=all" onClick="return confirm('Are you sure to clear you cart?');" class="btn btn-sm btn-danger">Empty Cart</a>
							</th>
                        </tr>
                    </thead>
                    <tbody>
						<?php
						require_once "dbconfig.php";
						$select_stmt=$db->prepare("SELECT * FROM cart");
						$select_stmt->execute();
						$grand_total = 0;
						while($row=$select_stmt->fetch(PDO::FETCH_ASSOC))
						{
						?>
                        <tr>
                            <td><img src="images/<?php echo $row["product_image"]; ?>" width="50" height="50"/> </td>
							
                            <td><?php echo $row["product_name"]; ?></td>
							
                            <td><?php echo number_format($row["product_price"],2); ?></td>
							
                            <td><input type="number" class="form-control itemQty" value="<?php echo $row['quantity']; ?>" style="width:75px;"></td>
							
                            <td class="text-right"><?php echo number_format($row["total_price"],2); ?></td>
							
                            <td class="text-right">
							<a href="action.php?remove=<?php echo $row["cart_id"];?>" onClick="return confirm('Are you sure want to remove this item?');"  class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></a> 
							</td>
							
							<input type="hidden" class="pid" value="<?php echo $row["cart_id"]; ?>"> 
							<input type="hidden" class="pprice" value="<?php echo $row["product_price"]; ?>">
							
							<?php $grand_total +=$row["total_price"]; ?>
                        </tr>
						<?php
						}
						?> 
                        
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>Sub-Total</td>
                            <td class="text-right"><?php echo number_format($grand_total,2); ?></td>
                        </tr>
						
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td> 
                            <td><strong>Total</strong></td>
                            <td class="text-right"><strong><?php echo number_format($grand_total,2); ?></strong></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="col mb-2">
            <div class="row">
                <div class="col-sm-12  col-md-6">
                    <a href="index.php" class="btn btn-block btn-light"><i class="fa fa-shopping-cart"></i> Continue Shopping</a>
                </div>
                <div class="col-sm-12 col-md-6 text-right">
					<a href="checkout.php" class="btn btn-md btn-block btn-success text-uppercase <?=($grand_total > 1)?"":"disabled"; ?>"> Checkout </a>
                </div>
            </div>
        </div>
    </div>

</div>





Display Item In Cart

10. Delete Specific Item In Cart

Each row in the shopping cart has an anchor tag (trash icon) that holds the ID of the cart table. Whenever the user clicks on any item for removal, a simple modal confirmation appears on the top panel and asks the user to remove it or not.


If the user approves, then sending a delete request for specific items to the back end file "action.php". The deleted item message will be shown in the header section of this page after the deletion process has been completed on that file.


<a href="action.php?remove=<?php echo $row["cart_id"];?>" onClick="return confirm('Are you sure want to remove this item?');"  class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></a> 

Fetch the specific item request below code to remove and delete it on the cart table. And send the message via the session method to the cart.php file.


if(isset($_GET["remove"]))
{
	$id = $_GET["remove"];
	$delete_stmt = $db->prepare("DELETE FROM cart WHERE cart_id =:cid");
	$delete_stmt->execute(array(":cid"=>$id));
	
	$_SESSION["showAlert"] = "block";	
	$_SESSION["message"] = "Item removed from the cart";
	header("location:cart.php");
}

Delete Specific Item In Cart

11. Delete All Items In Cart

As you can see in the shopping cart last < th > tag, there is an anchor tag called Empty Cart that holds the I d of the cart table. Whenever the user clicks on that, on the top panel, the simple confirm modal arises and asks the user to clear the cart.


If the user approves, submit the delete request to the action.php file. After the deletion procedure on this file is complete, all items deleted message will be shown in the header section of this page.


<th scope="col" class="text-right">
	<a href="action.php?clear=all" onClick="return confirm('Are you sure to clear you cart?');" class="btn btn-sm btn-danger">Empty Cart</a>
</th>

The code below is responsible for deleting all products from the cart table. After the task is complete, all item deletion messages will be sent via the session method to the cart.php file.


if(isset($_GET["clear"]))
{
	$id = $_GET["clear"];
	$delete_stmt = $db->prepare("DELETE FROM cart");
	$delete_stmt->execute();
	
	$_SESSION["showAlert"] = "block";	
	$_SESSION["message"] = "All item removed from the cart";
	header("location:cart.php");
}

Delete All Items In Cart

The code that I put in the cart.php file above < div class="container "> tag. This code shows an item deletes messages using the $ SESSION[] method.


<div style="display:<?php if(isset($_SESSION["showAlert"])){echo $_SESSION["showAlert"];} else { echo "none"; } unset($_SESSION["showAlert"])?>" class="alert alert-success alert-dismissible mt-2">
	<button type="button" class="close" data-dismiss="alert">&times;</button>
	<strong><?php if(isset($_SESSION["message"])){echo $_SESSION["message"];} unset($_SESSION["showAlert"]);?></strong> 	
</div>

12. Update Item Quantity In Cart

See one input type number tag in the shopping cart holding quantity values and two hidden input tag holding cart table Id and values of the product price. Using both, we update quantity values via the $.ajax() procedure.


<td><input type="number" class="form-control itemQty" value="<?php echo $row['quantity']; ?>" style="width:75px;"></td>

<input type="hidden" class="pid" value="<?php echo $row["cart_id"]; ?>"> 
<input type="hidden" class="pprice" value="<?php echo $row["product_price"]; ?>">

Let's understand the source code below codes dynamically increase or decrease quantity values and price without page refresh.


The on("change)" method first triggers when the user changes quantity values since we put .itemQty class attribute value.


Here, in the closest() method, we pass < tr > tag, and that step returns < tr > tag ancestor.


Here we pass the quantity input tag and two hidden input tag class attribute values. .pid, .pprice, and .itemQty. And the val() method gets all values.


location.reload(true);


The reload() method is used to reload the current document. This method does the same as the reload button in your browser. ( according to w3schools )


We use the great and fast $.ajax() method here to transfer the request for values to the action.php back-end file. The ajax request will be addressed silently with the HTTP POST method. Ajax code that shows updated quantities and overall price values in the shopping cart without refreshing the page.


<script type="text/javascript">
	$(document).ready(function(){ 
	
		$(".itemQty").on("change", function(){
			
			var hide = $(this).closest("tr");
			
			var id = hide.find(".pid").val();
			var price = hide.find(".pprice").val();
			var qty = hide.find(".itemQty").val();
			location.reload(true);
			$.ajax({
				url: "action.php",
				method: "post",
				cache: false,
				data: {pqty:qty, pid:id, pprice:price},
				success:function(response){ 
					console.log(response);		
				}
			});
		});	
	});
</script>

You know, all PHP code back-end files that work silently are written to action.php. This file is also located below the codes.


Ajax request data is derived from the responsibility of this code and the relevant item quantity and total price values in the cart table are quietly updated.


if(isset($_POST["pqty"]))
{
	$qty	= $_POST["pqty"];
	$id		= $_POST["pid"];
	$price	= $_POST["pprice"];
	
	$total_price = $qty * $price;
	
	$update_stmt=$db->prepare("UPDATE cart SET quantity=:qty, total_price=:ttl_price WHERE cart_id=:cid");
	$update_stmt->execute(array(":qty"=>$qty, 
								":ttl_price"=>$total_price, 
								":cid"=>$id));
}

Update Item Quantity In Cart

13. Checkout Item

Now we have everything prepared, it's time to wrap up the checkout page where customers can view and pay for their items. It's a good idea for consumers to apply taxes, delivery, and service charges along with the total amount on this page.


For the payment gateway, you can create any type of data here, most payment gateways preferred HTML form. I have two hidden input fields created, you can change them to match your requirements.


The code below begins above <! DOCTYPE html > in a file called checkout.php. The responsibility for these codes is to retrieve from the cart table the total number of quantities and price of products.






<?php
require_once "dbconfig.php";

$grand_total = 0;
$allItems = "";
$items = array();

$select_stmt=$db->prepare("SELECT CONCAT(product_name, '(', quantity,')') AS ItemQty, total_price FROM cart");
$select_stmt->execute();  
while($row=$select_stmt->fetch(PDO::FETCH_ASSOC))
{
	$grand_total = $grand_total + $row["total_price"];
	$items[] = $row["ItemQty"];
}
$allItems = implode(", ", $items);

?>





Explanation :


Declares the $grand_total variable and assigns a value of 0 (zero). 


Build a blank variable called $allItems. 


Build $items called in the blank array variable. 


Using the CONCAT() function, we add product_name and quantity fields in the ItemQty column in PDO select query.


$grand_total = $grand_total + $row["total_price"]; That count the total price of items.


$items[] = $row["ItemQty"]; - The $row["ItemQty"] contains the name of the product and the quantity values. And it will assign the $items[] array variable that above we have already built. The code displays the product name with the value of the total quantity. 


And using implode() function name and quantities values separately divided by the comma symbol and stored in the $allItems variable.


For example display this type:-  shirt(1), glass(2)


Code for the last final step,


The form below includes simple user requirements and two hidden input tags holding the name of the product and the total amount of products.






<form method="post" id="placeOrder">
			
	<input type="hidden" name="products" value="<?php echo $allItems ?>">
	<input type="hidden" name="grand_total" value="<?php echo $grand_total ?>">
				
	<div class="form-group">
		<input type="text" name="name" class="form-control" placeholder="enter name" required>
	</div>	
				
	<div class="form-group">
		<input type="email" name="email" class="form-control" placeholder="enter email" required>
	</div>
				
	<div class="form-group">
		<input type="tel" name="phone" class="form-control" placeholder="enter phone" required>
	</div>
				
	<div class="form-group">
		<textarea name="address" class="form-control" rows="3" cols="10" placeholder="enter address"></textarea>
	</div>
				
	<h6 class="text-center lead">Select Payment Mode</h6>
	<div class="form-group">
		<select name="pmode" class="form-control">
			<option value="">-- select payment --</option>
			<option value="cod">Cash On Delivery</option>
			<option value="netbanking">Net Banking</option>
			<option value="card">Debit/credit Card</option>
		</select>
	</div>
				
	<div class="form-group">
		<input type="submit" name="submit" class="btn btn-danger btn-block" value="Place Order">
	</div>
</form>





The following jQuery / Ajax code works without reloading the page and inserts data for new orders and displays an appropriate message.


The submit() event occurs when a form is submitted. This event can only be used on <form> elements. ( according to w3schools ).


Here we pass the form tag I d attribute #placeOrder and attach the serialize() method to form all value requests.


The ajax() method uses the HTTP POST method to send the request to the action.php file and view the order success response without refreshing the page.






<script type="text/javascript">
	$(document).ready(function(){ 
		$("#placeOrder").submit(function(e){
			
			e.preventDefault();
			
			$.ajax({
				url: "action.php",
				method: "post",
				data: $("form").serialize()+"&action=order",
				success: function(response){
					$("#showOrder").html(response);
				}
			});	 
		});
	
	});
</script>





The responsibility for this code is quietly receiving form requests through the ajax method and inserting new order information in the order table.


The source code was combined with HTML and PHP code because the colorful visual style of the order success message was presented.






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"];
	
	$data = "";
	
	$insert_stmt=$db->prepare("INSERT INTO orders(username,
												  email,
												  phone, 
												  address,
												  payment_mode,
												  products,
												  paid_amount) 
											VALUES
												 (:uname,
												  :email,
												  :phone,
											      :address,
												  :pmode,
												  :products,
												  :pamount)"); 					
	$insert_stmt->bindParam(":uname",$name);	
	$insert_stmt->bindParam(":email",$email);	
	$insert_stmt->bindParam(":phone",$phone);	
	$insert_stmt->bindParam(":address",$address);	 
	$insert_stmt->bindParam(":pmode",$pmode);	
	$insert_stmt->bindParam(":products",$products);	
	$insert_stmt->bindParam(":pamount",$grand_total);	
	$insert_stmt->execute();
	
	$data.='<div class="text-center">
				<h1 class="display-4 mt-2 text-danger">Thank You!</h1>
				<h2>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;		
}





Checkout Item

Learn More PDO Tutorials:

How to upload an image to a database using PHP PDO

How to Upload, Insert, Update and Delete File Using PHP PDO & MySQL

Multi User Role Based Login in PHP with MySQL PDO

Login and Register Script In PHP PDO With MySQL

Multiple Checkbox Value Add, Edit, Delete using PHP PDO with MySQL


Download Codes

297 comments:

  1. how to fetch separate products from cart for different persons using on different browser. Because it is fetching all products for every customers in the cart.

    ReplyDelete
    Replies
    1. Hi, I create only shopping cart system.
      Add register and login module and to store and checkout specific product on a login user account using the session method.

      Delete
  2. thanks a lot but how can i download the source code please

    ReplyDelete
    Replies
    1. Hi Lil Leart, only subscriber and Facebook page like user can download source code

      Delete
  3. how can we download the source code please

    ReplyDelete
    Replies
    1. go to end of this article and download all source code zip file.

      Delete
  4. please you don't have to disable copying the code we can view the source code of the page and copy it from it

    ReplyDelete
  5. not able to find source code zip file

    ReplyDelete
    Replies
    1. hi, recently I disabled source code zip for few reason, if you face any issue then contact me

      Delete
    2. Hi can you help me to download this files ?

      Delete
  6. how can I download this ?

    ReplyDelete
    Replies
    1. Hi, recently I disabled download source code zip for few reason, if you face any issue then contact me

      Delete
    2. hey can you send me code

      Delete
    3. i want the source code

      Delete
    4. I also have a blog like this
      codemanna.blogspot.com

      Delete
  7. i want source code of this project

    ReplyDelete
  8. hi, can i download this one? im having hard time in my proj :(

    ReplyDelete
    Replies
    1. Hi, recently I disabled download source code zip file for few reason. If you face any issue about your project then contact me

      Delete
  9. Kindly provide source code in zip , if you provide admin panel code , it will be grateful

    ReplyDelete
  10. Kindly provide source code

    ReplyDelete
  11. Replies
    1. go to end of tutorial and download source code zip file

      Delete
  12. where is the source code? i really need it to integrate in my project!

    ReplyDelete
    Replies
    1. Hi, recently I disabled download source code zip file for few reason. If you face any issue about your project then contact me

      Delete
  13. Hello,am lost abit i wanted to find out where u got cartItem and cart-item on
    $.ajax({

    url: "serverside/getcart.php",
    method: "get",
    data:{cartItem:"cart_item"},
    success : function(response) {
    $("#cart-item").html(response);
    },

    });

    ReplyDelete
    Replies
    1. Hi Maikabo, this ajax codes send request to your server file and server response total cart item value in the cart

      Delete
    2. Can you please undisable the source code so that i can copy please,do you have a video tutorial for this.

      Delete
  14. Hello. If you can send the source code or send an application video, please

    ReplyDelete
    Replies
    1. Hi, I'm upgrading source code after completed it I provide source code link

      Delete
    2. i subscribed and like page can you please send source code on [email protected]

      Delete
  15. thank you for this job so can you send code source for this project

    ReplyDelete
    Replies
    1. Hi, I'm upgrading source code after complete it I provide source code link

      Delete
  16. thank you so mutch my congratulations to you mr hamid you are very helpfull

    ReplyDelete
  17. Replies
    1. Hi, I'm upgrading source code after complete it I provide source code link

      Delete
  18. hello , the header code for cart is missing in the tutorial , could you please the code or total source code on my email

    ReplyDelete
    Replies
    1. OK, Send your email via contact form or subscribe your email in this blog

      Delete
  19. Hi, source code of css please..

    ReplyDelete
  20. Source code Download link available end of tutorial.

    ReplyDelete
  21. can you send me the source cod, please. Thank you!

    ReplyDelete
    Replies
    1. Hi, Aki only subscriber and Facebook like page user can download source code. Confirm your email subscription and like Facebook page. After I enable source code in your email to download

      Delete
    2. Hi, Hamid can you please enable source i my email, thank you.

      Delete
    3. I enable source code link your email check again and download

      Delete
  22. Replies
    1. I enable source code in your email check again and download

      Delete
  23. Hello!!can i have a source code, thanks!!
    I just really need the checkout codes for my project

    ReplyDelete
    Replies
    1. Hi Jhon, only subscriber and Facebook page like user can download source code

      Delete
  24. Hello admin, please can i have the source code

    ReplyDelete
    Replies
    1. Hi Jhon, only subscriber and Facebook page like user can download source code

      Delete
  25. Subscribed and liked.
    Can you add access to source code
    Email is [email protected]

    ReplyDelete
    Replies
    1. I enable source code link in your email download it

      Delete
  26. hey man i completed everything can u authorize me to download
    my email : [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it

      Delete
    2. Can I get the source code please?

      Delete
    3. Hi, only subscriber and Facebook page like user can download source code

      Delete
  27. can I get the source code?

    ReplyDelete
  28. hi where can i get the source code

    ReplyDelete
  29. hello, i subscribed. could you enable download for the source code please
    my email is [email protected]
    thank you

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  30. Hi kindly share the source code email: [email protected]. Thanks

    ReplyDelete
    Replies
    1. Your email not verify please verify your email.

      Delete
  31. hi can u kindly share your source code to this email? [email protected]
    thank you very much!

    ReplyDelete
  32. Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  33. Replies
    1. Sorry your are unverified please verify your email

      Delete
  34. hi, can you access my email
    [email protected]
    thankyouuu

    ReplyDelete
    Replies
    1. Sorry you are unverified, please verify your proper email address

      Delete
    2. can you email the source code to that email?

      Delete
    3. Subscribe required keep subscribe

      Delete
  35. Replies
    1. Hi, only subscriber and Facebook page like user can download source code

      Delete
  36. hi , do you have code for admin can see the order list from this cart

    ReplyDelete
    Replies
    1. No, I only created shopping cart module on the client side

      Delete
  37. Replies
    1. Sorry, you are unverified, please verify properly again

      Delete
  38. hi done subscribe and like. my email is [email protected]

    ReplyDelete
  39. Replies
    1. Sorry, you are unverified, please verify properly again

      Delete
  40. Hey, I just subscribed mail and liked fb. Can you send me the source code at my email? [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  41. Replies
    1. Hi, only subscriber and Facebook page like user can download source code

      Delete
  42. liked and subscribed. Please send me source code. My email is [email protected]

    ReplyDelete
    Replies
    1. I see you like FB page but you are unverified email, please verify email properly again

      Delete
  43. How can I download the source code?

    ReplyDelete
  44. Hi, just I subscribed. Can you send me the source code to [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  45. hola me puedes compartir tu codigo de tu proyeto plis
    [email protected]

    ReplyDelete
    Replies
    1. Hi, only subscriber and Facebook page like user can download source code

      Delete
  46. hola me puedes compartir tu proyecto plis...gracias

    ReplyDelete
    Replies
    1. Hi, only subscriber and Facebook page like user can download source code

      Delete
  47. I have confirmed subscription and Fb page like. Please can I get the link on [email protected]. Thanks

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  48. I also liked and subscribed. Please send me source code. My email is [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  49. I liked the page. Could you share with me the code? The email is: [email protected]

    ReplyDelete
  50. Hey i liked the FB page and subscribed for the newsletter could u please add me on the source code

    ReplyDelete
    Replies
    1. but you are unverified email, please verify email properly again

      Delete
  51. Subscribed, May you please share the codes email [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  52. Liked the fb page and subscribed, can you share the code through my email [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
    2. Sir, I like Your Fb Page and subscribed. Can you share above code on my email [email protected]

      Delete
  53. Hi Sir, can you share this code with me. I urgently need in my project.
    my Email : [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  54. I already like your Facebook page

    ReplyDelete
  55. Hi done like and. Subscribe please May you please share the code on my mail.

    ReplyDelete
  56. Subscribed, May you please share the source code on my email [email protected]
    Thanku!

    ReplyDelete
  57. Hi, I.ve subscribe to your and like your facebook page. plz help with the source code

    ReplyDelete
  58. Hi Hamid. Im subscribing to your account to get userful content. plz give access to the source code

    ReplyDelete
  59. Hi hamid, I Subcriberd. Can you share this code.
    My email:[email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  60. Hi hamid, Can u share this code i need to learn some code to this
    My email:[email protected]

    ReplyDelete
    Replies
    1. subscriber and Facebook page like user can download source code

      Delete
    2. Done subscribing and Like your page

      Delete
  61. Hi Hamid, I have subscribed and liked your page, could you share the code with me?
    Email: [email protected]

    Thank you.

    ReplyDelete
    Replies
    1. Sorry, I see your email not verify please verify properly again.

      Delete
    2. Hi, could you try with this email?
      Email: [email protected]

      Thank you.

      Delete
    3. Sorry this email is not verify, please verify

      Delete
  62. oh what generosity from you thank you so much

    ReplyDelete
  63. sir i wanted the source code of this project

    ReplyDelete
    Replies
    1. Hi Sparsh, only subscriber and Facebook page like user can download source code

      Delete
  64. sir i wanted the source code of this project.

    ReplyDelete
  65. Please how do i subscribe and i have shared on twitter

    ReplyDelete
    Replies
    1. No Problem Send your email here and Like Facebook page. I will share source code in your email. Keep Visiting

      Delete
  66. [email protected], i have liked your facebook page using [email protected]. please do send me the codes. tq

    ReplyDelete
  67. [email protected] can u send me source code ,i have liked your facebook page.

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  68. I have liked your facebook page, can you please send me the source code on [email protected]
    does this code work for easy digital download?

    ReplyDelete
    Replies
    1. Sorry for late reply after I upgrading codes I enable source code link in your email

      Delete
  69. Well done Hamid, your article is really awesome

    ReplyDelete
  70. Hi Hamid
    Would you please send through source code. I red through your comments regarding source code, I am also not able to find source code.

    ReplyDelete
    Replies
    1. after I upgrading source codes I enable source code link

      Delete
  71. sir please provide a source code

    ReplyDelete
    Replies
    1. after I upgrading codes I enable source code link

      Delete
  72. Hi there, please could you share the source code? I have liked the Facebook page and subscribed. Thank you so much:-)

    ReplyDelete
    Replies
    1. Hi Jacqui, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  73. Please provide source code [email protected]

    ReplyDelete
    Replies
    1. I verified my email [email protected] please send me that code

      Delete
    2. You don't like Facebook page please like it. After I enable source code link in your email

      Delete
    3. I subscribe your blog by this [email protected] email id & I follow & Like your Facebook page by this100009462968594 Facebook ID but my email address will not registered with those Facebook id, So Now you can send code in address [email protected], Thanks You & Your Content is awesome

      Delete
    4. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  74. Hi! Please share the source code. I have liked the facebook page and subscribed. Thany you.

    ReplyDelete
  75. Hi! Please let me download the source code.

    ReplyDelete
    Replies
    1. Hi, only subscriber and Facebook page like user can download source code

      Delete
  76. Replies
    1. Hi, only subscriber and Facebook page like user can download source code

      Delete
  77. Hi I already like your facebook page and subscribe can you please share the source code to this email? [email protected]

    ReplyDelete
    Replies
    1. Hi, this type of email id not allowed please use Gmail, Yahoo and Live mail address.

      Delete
  78. hi, already like and subscribe can you share the source code, thank you
    [email protected]

    ReplyDelete
  79. Hi , i already like and subscribe . Can you share the source code please . thank you.
    [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  80. Hi, I have subscribed and liked, can you share the source code ,thank you very much.
    [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  81. Hi, i already like and subscribed, can you share the source code? thank you
    [email protected]

    ReplyDelete
    Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
  82. hello, i already subscribe and liked. can you share the source code please? my email is [email protected]

    ReplyDelete
  83. I've been working on my cart for weeks and this is the only code that worked. Thank you so much! I hope you can also demonstrate how to check out only specific or checked items from cart. It would mean a lot for beginners like me. Thank you!

    ReplyDelete
  84. hi can you give access to my mail id.

    ReplyDelete
  85. Replies
    1. OK, I enable source code link in your email check again and download it. Keep Visiting

      Delete
    2. Ok I enable source code link in your email check again and download it

      Delete
  86. Hi can you give me access to download the files ? please

    ReplyDelete
    Replies
    1. only subscriber and Facebook page like users can download source code link

      Delete
  87. Hi! Can i get access to source code please? My e-mail is [email protected]

    ReplyDelete
    Replies
    1. Only subscriber and Facebook page like user can download source code. Complete two thing first.

      Delete
  88. can you plss send me the codes i have subscribed
    [email protected]

    ReplyDelete
    Replies
    1. Ok I enable source code link in your email check again and download it

      Delete
  89. i am not able to download it. Please suggest the best way

    ReplyDelete
  90. hello and thank for great code. Can you please ad me to download list? my mail is [email protected]

    ReplyDelete
    Replies
    1. your email not verified please verify your email

      Delete
  91. Hi
    I suscribed to your Facebook page and your newsletter [email protected]
    Could I have the code please ?

    ReplyDelete
    Replies
    1. Sorry this type of email not allowed please use Gmail, yahoo, live

      Delete

Post Bottom Ad