$(document).ready(function() {
// add to cart
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { product_id: "123", product_name: "Some Product", product_price: '$50' },
dataType: "json",
success: function(data) {
console.log(data);
// on success remove this element from markup
$(_this).remove(); // "_this" is element we are removing not "this"
},
error: function(data) {
console.log("Ajax Error");
}
});
});
// remove from cart
// we will use delegate here
$(document).on('click', '.cart-remove', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { remove_item: "123" },
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("Ajax Error");
}
});
});
});
<?php
// start session
session_start();
if(isset($_POST["remove_item"])) {
// we will remove item from session array based on this index
$index = $_POST["index"];
/**
* if aray has only 1 item, unset session var
* if not, remove only this item form the session
*/
if(count($_SESSION["cart"]) <= 1) {
unset($_SESSION["cart"]);
}else {
unset($_SESSION["cart"][$index]);
}
// set the response
$response = count($_SESSION["cart"]);
$json = json_encode($response);
echo $json;
}
<?php
/**
* @author Ivan Milincic <lokomotivan@gmail.com>
*
*/
// start session
session_start();
// create data array
$data = array();
/*
* if $_SESSION["cart"] exists
* asign it to $data array so we can keep existing $_SESSION["cart"] data
*
*/
if(isset($_SESSION["cart"])) {
$data = $_SESSION["cart"];
}
if(isset($_POST["product_id"])) {
/**
* lets add random array index to this item
* so we can reference to it later on when we want to remove item from cart
*/
$rand = rand(0, 100);
$index = "product-$rand";
// new product array
$product = array(
"index" => $index,
"id" => $_POST["product_id"],
"name" => $_POST["product_name"],
"price" => $_POST["product_price"],
);
// add new product to $data array with custom index
$data[$index] = $product;
// set/update $_SESSION["cart"]
$_SESSION["cart"] = $data;
// encode and return json response
$json = json_encode($data);
echo $json;
}