Below is a my CRUD code for a shopping cart using AngularJS;
$scope.items = <?php echo json_encode($item_array); ?>;
$scope.cart = [];
$scope.deleteItem = function(item) {
var cart = $scope.cart;
var match = getMatchedCartItem(item);
if (match.count) {
cart.splice(cart.indexOf(item), 1);
return;
}
}
$scope.addItem = function(item) {
var match = getMatchedCartItem(item);
if (match) {
match.count += 1;
return;
}
var itemToAdd = angular.copy(item);
itemToAdd.count = 1;
$scope.cart.push(itemToAdd);
}
$scope.incQty = function(item) {
var match = getMatchedCartItem(item);
if (match) {
match.count += 1;
return;
}
}
$scope.decQty = function(item) {
var cart = $scope.cart;
var match = getMatchedCartItem(item);
if (match.count > 1) {
match.count -= 1;
return;
}
cart.splice(cart.indexOf(item), 1);
}
$scope.subTotal = function() {
var subtotal = 0;
for (var i = 0, max = $scope.cart.length; i < max; i++) {
subtotal += $scope.cart[i].price * $scope.cart[i].count;
}
$scope.subtotal = subtotal;
}
$scope.calcTotal = function() {
var total = 0;
for (var i = 0, max = $scope.cart.length; i < max; i++) {
total += $scope.cart[i].price * $scope.cart[i].count;
}
$scope.total = total + $scope.qwickCharge;
}
With the above, I'm saving everything using localStorage and cookies.
So a user can return and I just retrieve their cart from localStorage or cookies.
Obviously that is not a secure way of doing things.
What I want to be able to do is persist the cart to MySQL DB and reference it using a $_COOKIE
or $_SESSION
.
Can anyone assist me with how to embed angular $http
to post to my .php
script server side. I don't need the php code. Just the AngularJS code so as part of $scope.deleteItem for example I post to my db the item deleted and I can handle deleting it from my cart table.
FYI: item is an array containing name,qty,price etc