receive post variables in an ajax and process the data and print them in an html table to show the compass cart without updating page

0

I am a newbie in web programming and made a shopping cart using SESSIONES, in which I add products through a form that is contained in a container this form has a submit button, which sends the data of the selected product by the post method this is my code where I have my container where I show each product that the user selects and send it to my shopping cart:

 <div class="card-content">
                             <span class="card-title red-text">Productos</span>


                                     <div class=" row">
                                         <?php  $sel=$con->prepare("SELECT*FROM Producto where cod_catego1 =3 ");
                                         $sel->execute();
                                         $res=$sel->get_result();
                                         $row=mysqli_num_rows($res);

                                         while($f=$res->fetch_assoc()){

                                            ?>
                                         <div class="card col s3 ">
                                             <form action="index.php?action=add&code=<?php echo $f["cod_producto"]; ?>" method="post" >
                                                 <div class="card-image">
                                                 <img src="<?php echo $f['imagen'] ?>" width="50" height="180">
                                                 <!-- <span class="card-title">Card Title</span> -->
                                                 </div>
                                                 <div class="card-content  purple-text">
                                                     <p><?php echo $f['nombrep'] ?></p>
                                                     <p><?php echo $f['modelo'] ?></p>
                                                 </div>
                                                 <!-- <div class="card-action"> -->
                                                     <input type="number"  value="1" name="quantity" min="1"  class=" col s6 blue-text " autocomplete="off">
                                                    <input type="hidden" name="hidden_name" value="<?php echo $f["nombrep"]; ?>" />
                                                    <input type="hidden" name="hidden_price" value="<?php echo $f["precio"]; ?>" />
                                                    <button class="btn btn-floating orange " type="submit" name="add_to_cart"><i class="material-icons right">add_shopping_cart</i></button>
                                                    <button data-target="modal1" data-id="<?php echo $f["cod_producto"]; ?>"  value="<?php echo $f["modelo"]; ?>"  class="btn modal-trigger ver"><i class="material-icons">visibility</i></button>

                                                     <div class="card-content">
                                                         <p class="red-text "><?php echo "$ ".number_format($f['precio'],2); ?></p>
                                                     </div>
                                                 </form>

                                             <!-- </div> -->

                                         </div>

                                         <!-- Modal Structure -->


                                         <?php

                                     }

                                     ?>

         </div><!-- fin de row container de pruductos-->

                         </div>

After sending the data of the product by the post method I receive them in the same index.php, this is the code that receives the data and loads them to the shopping cart using sessions:

<?php include '../extend/header.php';



if(isset($_POST["add_to_cart"]))
{
    if(isset($_SESSION["shopping_cart"]))
    {
        $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
        if(!in_array($_GET["code"], $item_array_id))
        {
            $count = count($_SESSION["shopping_cart"]);
            $item_array = array(
                'item_id'           =>  $_GET["code"],
                'item_name'         =>  $_POST["hidden_name"],
                'item_price'        =>  $_POST["hidden_price"],
                'item_quantity'     => $_POST["quantity"]
            );
            // $_SESSION["shopping_cart"][$count] = $item_array;

            array_push($_SESSION['shopping_cart'], $item_array);
            header('location:../ope/index.php?code=0');// asigno valor a variable code= a cero para evitar que recarge la pagina con el valor
        }
        else if(in_array($_GET["code"], $item_array_id))
        {

            foreach($_SESSION["shopping_cart"] as $keys => $values)
            {
                if($values["item_id"] == $_GET["code"])
                {
                    $_SESSION["shopping_cart"][$keys]['item_quantity']+=$_POST["quantity"];

                      header('location:../ope/index.php?code=0');// asigno valor a variable code= a cero para evitar que recarge la pagina con el valor


                }
            }
             // echo '<script>alert("Producto agregado")</script>';

        }
    }
    else
    {
         header('location:../ope/index.php?code=0');
        $item_array = array(
            'item_id'           =>  $_GET["code"],
            'item_name'         =>  $_POST["hidden_name"],
            'item_price'        =>  $_POST["hidden_price"],
            'item_quantity'     =>  $_POST["quantity"]
        );
        $_SESSION["shopping_cart"][0] = $item_array;

    }

}

if(isset($_GET["action"]))
{
    if($_GET["action"] == "delete")
    {
        foreach($_SESSION["shopping_cart"] as $keys => $values)
        {
            if($values["item_id"] == $_GET["code"])
            {
                unset($_SESSION["shopping_cart"][$keys]);
                echo '<script>alert("eliminar producto")</script>';
                echo '<script>window.location="index.php"</script>';
            }
        }
    }
}



if (isset($_GET["action"])) {
    // code...

        if($_GET["action"] == "deleteAll") {
        // code...
                unset($_SESSION["shopping_cart"]);
    }

}
?>

once I have created the session of the shopping cart I show the data in a table to print the products and the user see this is the code where I show the contents of the cart to the user:

  <div class="card-content">
      <span class="card-title red-text"><i class="material-icons blue-text">shopping_cart</i>Lista de productos</span>

                <label class="waves-light right red-text">ELIMINAR TODO</label>
                <a href="#"     onclick="alartaDeleteProduct()"><i class="material-icons red-text right ">delete</i></a>
                  <table class="centered responsive-table highlight  white">
          <thead>
                            <th>Codigo Producto</th>
            <th>nombre</th>
            <th>cantidad</th>
            <th>Precio Unitario</th>
                            <th>Sub Total</th>
            <th>eliminar</th>

                        </thead>
                        <?php
                        if(!empty($_SESSION["shopping_cart"]))
                        {
                            $total = 0;
                            foreach($_SESSION["shopping_cart"] as $keys => $values)
                            {
                        ?>
                        <tr class="blue-text">
                            <td><?php echo $values["item_id"]; ?></td>
                            <td><?php echo $values["item_name"]; ?></td>
                            <td><?php echo $values["item_quantity"]; ?></td>
                            <td>$ <?php echo number_format($values["item_price"],2); ?></td>
                            <td>$ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
                            <td><a href="index.php?action=delete&code=<?php echo $values["item_id"]; ?>"><i class="material-icons red-text">highlight_off</i></a></td>
                        </tr>

                        <?php
                                $total = $total + ($values["item_quantity"] * $values["item_price"]);
                            }
                        ?>

                        <?php
                        }
                        ?>



        </table>
                            <?php if (empty($total)) {
                                ?>
                            <label class="red-text waves-light"> <h5>Total: $ 0.0</h5></label>
                        <?php   }else {?>
                                <label class="red-text waves-light"> <h5>Total: $ <?php echo number_format($total, 2); ?></h5></label>
                                <!-- boton buttonEnd que termina el proceso de ñla cotizacion manda a la funcion js en la carpeta extends ala funcion alartaTreminarCarrito() -->
                                        <a  class="btn pink " onclick="alartaTreminarCarrito()" >Terminar<i class="material-icons right">playlist_add_check</i></a>
                    <?php } ?>





    </div>

So far everything works fine without problems, what I was checking, is how to do it through ajax so that I do not have to reload the page to update the data of my cart, I tried it and nothing does not turn out to be a mistake. , only works without ajax my question is how can I process the request to add products to cart without having to reload the website greetings.

    
asked by jose 08.05.2018 в 07:51
source

0 answers