Add to Cart and Checkout Code in PHP - Onlyxcodes - onlyxcodes

Sunday, 25 October 2020

Add to Cart and Checkout Code in PHP - Onlyxcodes

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. Tools and 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. Tools And Technology

Software :


Notepad++ : Download. All the source code made by this project is in this editor.

XAMPP Server: Download. The XAMPP as a localhost server, we build MySQL database connections and run our project on this server.


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. The reload() 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

Download Codes

No comments:

Post a comment