Thursday 30 August 2018

Create Shopping Cart Application using AngularJS with PHP



In this post we have will make simple online shopping cart application by using AngularJS with PHP script. Here we have use PHP script from make shopping cart app in AngularJS, because AngularJS is a client front-end web application development javascript framework. So, if buyer has add some product into cart then product will be store under shopping cart, but if buyer has refresh web page then all shopping cart data will be lost, so here when again user visit shopping cart page then he can view product which he has added into cart. For this here we have use PHP script with AngularJS for developing simple shopping cart application. In this application we have use PHP SESSION variable for store shopping cart data and this data will be access across the site. So, if page refresh or buyer close site and again go to shopping cart site then he can view all product which he had added into cart.

This is simple web application in which buyer can add product into shopping cart which he want to buy from list of product and he can view shopping cart details like which product he has added into cart with all product details like name, price, quantity and remove button. Here for make shopping cart we have use AngularJS to implement some basic task like add product into cart, remove product from cart. For this all shopping cart operation we have use AngularJS as front-end development and for back-end we have use PHP script.









Load Product using AngularJS with PHP


In AngularJS Shopping cart application first we want to load product on web page with Add to cart button. Here we have store product details under Mysql database, so below you can find in javascript code in which we have make one loadProduct() function. This function send Ajax request to PHP script for fetch data from Mysql database and PHP script will send back product data to Ajax request which we have store under $scope.product expression and by using ng-repeat directive we have display on web page. But we want to called this function on page load, so by using ng-init directive we have add this loadProduct() function, this directive will called this function when page has been load into browser and it will list product on web page. Below you can find source code for this.





index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct()">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
                      $scope.products = data;
                })
 };
 
});
</script>


fetch.php



<?php

//fetch.php

$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");

$query = "SELECT * FROM tbl_product";
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
 $data[] = $row;
}

echo json_encode($data);

?>


Load Cart Details using AngularJS with PHP


Once all product has been display on web page by using AngularJS with PHP. Now we want to display buyer shopping cart details on web page using AngularJS with PHP. For this we have make fetchCart() AngularJS function. This function has send ajax request to fetch_cart.php page. Under this fetch_cart.php file script has been fetch data from $_SESSION variable. Here we have use PHP $_SESSION variable for store shopping cart data. So php script will convert this $_SESSION variable data into json string by using json_encode() function return back ajax success function which has been store under $scope.carts expression.

Now we want to display cart details on web page in table format, for this we have use ng-repeat directive. By using this directive it will display shopping cart details on web page. Now we want to display total of whole shopping cart at then end of cart. For this we have make new function setTotals(). This function will return total of whole shopping cart and total will be display in shopping cart. Lastly we want to load cart details on web page load. So this function also we have add into ng-init directive. So when page has been load this function will be called and buyer can see his shopping cart details on web page load.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct(); fetchCart();">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
   <br />
   <h3 align="center">Your Cart Details</h3>
   <div class="table-responsive" id="order_table">
    <table class="table table-bordered table-striped">
     <tr>  
      <th width="40%">Product Name</th>  
      <th width="10%">Quantity</th>  
      <th width="20%">Price</th>  
      <th width="15%">Total</th>  
      <th width="5%">Action</th>  
     </tr>
     <tr ng-repeat = "cart in carts">
      <td>{{cart.product_name}}</td>
      <td>{{cart.product_quantity}}</td>
      <td>{{cart.product_price}}</td>
      <td>{{cart.product_quantity * cart.product_price}}</td>
      <td><button type="button" name="remove_product" class="btn btn-danger btn-xs" ng-click="removeItem(cart.product_id)">Remove</button></td>
     </tr>
     <tr>
      <td colspan="3" align="right">Total</td>
      <td colspan="2">{{ setTotals() }}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
            $scope.products = data;
        })
 };
 
 $scope.carts = [];
 
 $scope.fetchCart = function(){
  $http.get('fetch_cart.php').success(function(data){
            $scope.carts = data;
        })
 };
 
 $scope.setTotals = function(){
  var total = 0;
  for(var count = 0; count<$scope.carts.length; count++)
  {
   var item = $scope.carts[count];
   total = total + (item.product_quantity * item.product_price);
  }
  return total;
 };
 
});

</script>


fetch_cart.php



<?php

//fetch_cart.php

session_start();

if(isset($_SESSION["shopping_cart"]))
{
 echo json_encode($_SESSION["shopping_cart"]); 
}


?>


Add Item into Cart using AngularJS with PHP


This is main task of shopping cart, how to add product or item add into cart using AngularJS with PHP. For this also we have make AngularJS function, this function has been called by using ng-click directive which we have use with Add to cart button. So when buyer has click particular product add to cart button then it will called addtoCart() function using ng-click directive. Under this function it has send product details get from addtoCart() function argument in array format using Ajax request send to add_item.php script.

At PHP script side data has been received json format and that data has been get using file_get_contents() and by using json_decode() function it has been converted into PHP array object. After this it will make new $_SESSION variable if buyer add first item and add product details under that session variable in array format. But suppose buyer already added same item into cart then only particular item quantity will be increase.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct(); fetchCart();">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
   <br />
   <h3 align="center">Your Cart Details</h3>
   <div class="table-responsive" id="order_table">
    <table class="table table-bordered table-striped">
     <tr>  
      <th width="40%">Product Name</th>  
      <th width="10%">Quantity</th>  
      <th width="20%">Price</th>  
      <th width="15%">Total</th>  
      <th width="5%">Action</th>  
     </tr>
     <tr ng-repeat = "cart in carts">
      <td>{{cart.product_name}}</td>
      <td>{{cart.product_quantity}}</td>
      <td>{{cart.product_price}}</td>
      <td>{{cart.product_quantity * cart.product_price}}</td>
      <td><button type="button" name="remove_product" class="btn btn-danger btn-xs" ng-click="removeItem(cart.product_id)">Remove</button></td>
     </tr>
     <tr>
      <td colspan="3" align="right">Total</td>
      <td colspan="2">{{ setTotals() }}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
            $scope.products = data;
        })
 };
 
 $scope.carts = [];
 
 $scope.fetchCart = function(){
  $http.get('fetch_cart.php').success(function(data){
            $scope.carts = data;
        })
 };
 
 $scope.setTotals = function(){
  var total = 0;
  for(var count = 0; count<$scope.carts.length; count++)
  {
   var item = $scope.carts[count];
   total = total + (item.product_quantity * item.product_price);
  }
  return total;
 };
 
 $scope.addtoCart = function(product){
  $http({
            method:"POST",
            url:"add_item.php",
            data:product
        }).success(function(data){
   $scope.fetchCart();
        });
 };
 
});

</script>


add_item.php



<?php

//add_item.php

session_start();
$product_data = json_decode(file_get_contents("php://input"));
$product_id = $product_data->id;
$product_name = $product_data->name;
$product_price = $product_data->price;

if(isset($_SESSION["shopping_cart"]))
{
 $is_available = 0;
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  if($_SESSION["shopping_cart"][$keys]['product_id'] == $product_id)
  {
   $is_available++;
   $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + 1;
  }
 }
 if($is_available == 0)
 {
  $item_array = array(
   'product_id'               =>     $product_id,  
   'product_name'             =>     $product_name,  
   'product_price'            =>     $product_price,  
   'product_quantity'         =>     1
  );
  $_SESSION["shopping_cart"][] = $item_array;
 }
}
else
{
 $item_array = array(
  'product_id'               =>     $product_id,  
  'product_name'             =>     $product_name,  
  'product_price'            =>     $product_price,  
  'product_quantity'         =>     1
 );
 $_SESSION["shopping_cart"][] = $item_array;
 
}
//print_r($_SESSION["shopping_cart"]);

?>


Remove Item From Cart using AngularJS with PHP


Lastly in AngularJS Shopping Cart application we want to see how can buyer can remove item from shopping cart. For this also we have create one removeItem() function. This function will remove particular product item from shopping cart when buyer click on remove button of particular item in shopping cart. This function has been called by using ng-click event of remove button. This function has send Ajax request to remove_item.php script and this script will be remove particular item from $_SESSION variable based on value of id using PHP unset() function and after removing remaining shopping cart details on web page.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Shopping Cart using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container" ng-app="shoppingCart" ng-controller="shoppingCartController" ng-init="loadProduct(); fetchCart();">
   <br />
   <h3 align="center">PHP Shopping Cart using AngularJS</h3>
   <br />
   <form method="post">
    <div class="row">
     <div class="col-md-3" style="margin-top:12px;" ng-repeat = "product in products">
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
       <img ng-src="images/{{product.image}}" class="img-responsive" /><br />
       <h4 class="text-info">{{product.name}}</h4>
       <h4 class="text-danger">{{product.price}}</h4>
       <input type="button" name="add_to_cart" style="margin-top:5px;" class="btn btn-success form-control" value="Add to Cart" ng-click="addtoCart(product)" />
      </div>
     </div>
    </div>
   </form>
   <br />
   <h3 align="center">Your Cart Details</h3>
   <div class="table-responsive" id="order_table">
    <table class="table table-bordered table-striped">
     <tr>  
      <th width="40%">Product Name</th>  
      <th width="10%">Quantity</th>  
      <th width="20%">Price</th>  
      <th width="15%">Total</th>  
      <th width="5%">Action</th>  
     </tr>
     <tr ng-repeat = "cart in carts">
      <td>{{cart.product_name}}</td>
      <td>{{cart.product_quantity}}</td>
      <td>{{cart.product_price}}</td>
      <td>{{cart.product_quantity * cart.product_price}}</td>
      <td><button type="button" name="remove_product" class="btn btn-danger btn-xs" ng-click="removeItem(cart.product_id)">Remove</button></td>
     </tr>
     <tr>
      <td colspan="3" align="right">Total</td>
      <td colspan="2">{{ setTotals() }}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('shoppingCart', []);

app.controller('shoppingCartController', function($scope, $http){
 
 $scope.loadProduct = function(){
  $http.get('fetch.php').success(function(data){
            $scope.products = data;
        })
 };
 
 $scope.carts = [];
 
 $scope.fetchCart = function(){
  $http.get('fetch_cart.php').success(function(data){
            $scope.carts = data;
        })
 };
 
 $scope.setTotals = function(){
  var total = 0;
  for(var count = 0; count<$scope.carts.length; count++)
  {
   var item = $scope.carts[count];
   total = total + (item.product_quantity * item.product_price);
  }
  return total;
 };
 
 $scope.addtoCart = function(product){
  $http({
            method:"POST",
            url:"add_item.php",
            data:product
        }).success(function(data){
   $scope.fetchCart();
        });
 };
 
 $scope.removeItem = function(id){
  $http({
            method:"POST",
            url:"remove_item.php",
            data:id
        }).success(function(data){
   $scope.fetchCart();
        });
 };
 
});

</script>


remove_item.php



<?php

//remove_item.php

session_start();

$product_data = json_decode(file_get_contents("php://input"));
$product_id = $product_data;

foreach($_SESSION["shopping_cart"] as $keys => $values)
{
 if($values["product_id"] == $product_id)
 {
  unset($_SESSION["shopping_cart"][$keys]);
 }
}

?>


So, here we have created simple shopping cart application using AngularJS with PHP. This tutorial will give you some idea regarding how to create shopping cart with AngularJS and PHP. For more updates regarding web development tutorials, you just stay connected with our website and learn new things and enjoy coding!






2 comments:

  1. You rock particularly for the high caliber and results-arranged offer assistance. I won't reconsider to embrace your blog entry to anyone who needs and needs bolster about this region. We are providing angularJs training in velchery.
    for more details:AngularJs training in chennai

    ReplyDelete