【发布时间】:2017-06-11 16:44:58
【问题描述】:
我正在构建一个购物车。我希望这样每次有人点击提交以将商品添加到他们的购物车时,它都会添加该商品,但它会保留在当前页面上而不刷新。然后,如果他们点击购物车图标,它会将他们带到他们物品所在的单独页面。使用下面的 PHP,我可以提交商品,它们会显示在购物车页面中,但提交按钮仍会刷新购物页面。
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "root", "tut");
if(isset($_POST["add"]))
{
if(isset($_SESSION["cart"]))
{
$item_array_id = array_column($_SESSION["cart"], "product_id");
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["cart"]);
$item_array = array(
'product_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'product_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["cart"][$count] = $item_array;
echo '<script>window.location="index.php"</script>';
}
else
{
echo '<script>alert("Products already added to cart")</script>';
echo '<script>window.location="index.php"</script>';
}
}
else
{
$item_array = array(
'product_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'product_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["cart"] as $keys => $values)
{
if($values["product_id"] == $_GET["id"])
{
unset($_SESSION["cart"][$keys]);
echo '<script>alert("Product has been removed")</script>';
echo '<script>window.location="thebag.php"</script>';
}
}
}
}
?>
<div id="mainform">
<div id="form">
<form method="post" action="index.php?action=add&id=<?php echo $row["id"]; ?>" id="myForm">
<h5 class="text-info"><?php echo $row["p_name"]; ?></h5>
<h5 class="text-danger">$ <?php echo $row["price"]; ?></h5>
<input type="hidden" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="<?php echo $row["p_name"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>">
<input type="submit" name="add" value="Submit">
</form>
</div>
</div>
【问题讨论】:
标签: php html forms post shopping