Избегайте перенаправления в действии записи PHP - PullRequest
0 голосов
/ 09 мая 2020

Итак, у меня есть эта форма, и когда я нажимаю на поле ввода для отправки, меня перенаправляют на URL-адрес действия. Как я могу этого избежать и оставаться на том же URL?

 ...
<form method="post" action="cart.php?action=add&pid='.$row["id"].'">
  <div class="cart-action" style="width: 100%;">
    <div class="input-group mb-3">
      <div class="input-group-prepend">
        <button class="btn btn-outline-primary js-btn-minus" type="button">−</button>
      </div>
      <input type="text" class="product-quantity form-control text-center"  name="quantity" value="1" size="2" placeholder="">
      <div class="input-group-append">
        <button class="btn btn-outline-primary js-btn-plus" type="button">+</button>
      </div>
    </div>
    <input type="submit" value="Agregar al carro" class="btnAddAction btn btn-outline-secondary" style="width: 100%;">
  </div>
</form>
...

А это код для добавления товара в корзину

    //code for Cart
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
    //code for adding product in cart
    case "add":
        if(!empty($_POST["quantity"])) {
            $pid=$_GET["pid"];
            $result=mysqli_query($con,"SELECT * FROM tblproduct WHERE id='$pid'");
              while($productByCode=mysqli_fetch_array($result)){
            $itemArray = array($productByCode["code"]=>array('name'=>$productByCode["name"], 'code'=>$productByCode["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode["price"], 'image'=>$productByCode["image"]));
            if(!empty($_SESSION["cart_item"])) {
                if(in_array($productByCode["code"],array_keys($_SESSION["cart_item"]))) {
                    foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productByCode["code"] == $k) {
                                if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                    $_SESSION["cart_item"][$k]["quantity"] = 0;
                                }
                                $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
                            }
                    }
                } else {
                    $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                }
            }  else {
                $_SESSION["cart_item"] = $itemArray;
            }
        }
    }
    break;

}
}

Спасибо

Ответы [ 3 ]

0 голосов
/ 09 мая 2020

Есть несколько способов сделать это. Это один:

Шаг 1: Добавьте скрытый ввод, который включает URL-адрес текущей страницы

<?php
   $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>

<input type="hidden" name="url" value=<?=$url;?>"

Шаг 2: Затем в вашем cart. php, вам нужно добавить перенаправление после добавления продукта, например

if(!empty($_GET["action"])) {
switch($_GET["action"]) {
    //code for adding product in cart
    case "add":
        if(!empty($_POST["quantity"])) {
            $pid=$_GET["pid"];
            $result=mysqli_query($con,"SELECT * FROM tblproduct WHERE id='$pid'");
              while($productByCode=mysqli_fetch_array($result)){
            $itemArray = array($productByCode["code"]=>array('name'=>$productByCode["name"], 'code'=>$productByCode["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode["price"], 'image'=>$productByCode["image"]));
            if(!empty($_SESSION["cart_item"])) {
                if(in_array($productByCode["code"],array_keys($_SESSION["cart_item"]))) {
                    foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productByCode["code"] == $k) {
                                if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                    $_SESSION["cart_item"][$k]["quantity"] = 0;
                                }
                                $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
                            }
                    }
                } else {
                    $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                }
            }  else {
                $_SESSION["cart_item"] = $itemArray;
            }
        }
    }
    header("Location: ".$_POST['url']);
    break;

}
}
0 голосов
/ 09 мая 2020

Вы можете перенаправить пользователя обратно на предыдущий URL, используя заголовки .

header("Location: previous_page.php");
0 голосов
/ 09 мая 2020

Вы должны использовать ajax

$("form").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');

    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
    });
});
...