简体   繁体   中英

How to make a product add to cart with ajax?

I am creating an e-commerce web page, it is almost done, but i notice that at the time of adding a product to the cart it redirects to the beginning of the products section (that is, in product 1) on the PC it does not affect almost anything because that the products can be shown on the entire screen, but if you are on a mobile device and you added 1 product that is very down, this would be very tedious, at first i tried to add a redirection to the product id in the action of the form and thus avoid going at the beginning, but this redirection is awful and can make the client dizzy. Then try to do it with ajax, I already reviewed other posts and I even saw tutorials but none of them work for me. What I want is that when I press add to cart, it gets added. Here are parts of the code:

products section:

        <div class="container">
        <div class="back-container"><button class ="back" onclick="location.href='productos.php'"><i class="fa-solid fa-arrow-left-long"></i></button></div>
            <section class="Productos">
                <article class="panrallado-grimaldi">
                        <h1>Pan Rallado</h1>      
                        <div class="productos">
                        <?php
                            $select_products = $connect->prepare("SELECT * FROM `productos` WHERE categoria='pr'") or die('query failed');
                            $select_products->execute();
                            $list_products = $select_products->fetchAll(PDO::FETCH_ASSOC);  
                            foreach($list_products as $producto){
                            include 'productact.php'; } ?>                    
                        </div>
                </article>     
            </section>
        </div>
    </main>
<script src="function.js"></script>
<script>
    $('body').on('submit', '.formadd', function(ev){
   var id = $(this).attr('id');
      $.ajax({
        type: 'POST',
        url: 'backend/addCart.php',

        data: $(id).serialize(),

            success: function(data) {
            $('.nav').load(' .nav');
            },
            error: function() {
                alert('No se pudo agregar al carrito, intente mas tarde');
            }
        });
        ev.preventDefault();
    });
</script>
</body>
</html>   

productadd(form to all products):

<?php 
$id = $producto['id'];
$codigo = $producto['codigo'];
$imagen = "media/productos/$codigo.png";
$nombre = $producto['nombre'];                   
$precio = $producto['precio']; 
$bulto = $producto['bulto']                
?>
<div class="p" id="<?php echo $id?>">
    <img src="<?php echo $imagen; ?>" alt="<?php echo $nombre?>" title="<?php echo $nombre?>">
    <p ><?php echo $nombre; ?></p>
    <form action="backend/addCart.php" class="formadd" id="<?php echo $id?>" method="post">
        <?php if(isset($_SESSION['email'])){?>
            <p>(x <?php echo $bulto; ?>)</p>
            <p class="precioo pps">$<?php echo number_format($precio, 0, ',', '.') ?></p>                                    
            <input type="hidden" name="id" value="<?php echo openssl_encrypt($id,COD,KEY);?>">
            <input class="cantidad pps" type="number" min="1" name="cantidad" class="cantidad" placeholder="1">   
            <div class="cc"><button type="submit" name="btnCart" value="Add" class="c pps">Agregar Al carrito</button></div>
            <?php
            } 
            ?>
    </form>
</div>

addCart.php (fucntion where the product is added):

    <?php
if(!isset($_SESSION)) { 
    session_start(); 
  };
  include 'connect.php';
  include 'config.php';

if (isset($_POST['id'])) {
            if(is_numeric(openssl_decrypt( $_POST['id'], COD, KEY))){
                $ID = openssl_decrypt( $_POST['id'], COD, KEY);                        
            }else{ echo '<script> alert("ID incorrecto"); </script>'; exit;
            }
            if($_POST['cantidad']<1){
            $CANTIDAD = 1;
            }else{                          
                $CANTIDAD = $_POST['cantidad'];
            }
            if(!isset($_SESSION['cart'])){
                $producto=array(
                    'ID'=>$ID,
                    'CANTIDAD'=>$CANTIDAD,
                );
                $_SESSION['cart'][0] = $producto;
                echo '
                <script>alert("Producto Añadido Exitosamente")</script>';
            }else{
                $idProductos=array_column($_SESSION['cart'],"ID");
                if(in_array($ID, $idProductos)){
                    echo
                    '<script>alert("El Producto Ya Ha Sido Agregado")</script>';  
                
                }else{
                    $producto=array(
                        'ID'=>$ID,
                        'CANTIDAD'=>$CANTIDAD,
                    );
                    array_push($_SESSION['cart'], $producto);  
                    echo '
                    <script>alert("Producto Añadido Exitosamente")</script>'       ;            
                }
            }
        }
?>

the problem it is the form success and do the action that i put on success: function(data) but the product doesnt add to cart. And chrome console doesnt show any error.

i´ve already done it. If anyone wanna know, here is the ajax code:

$('.formadd').on('submit', function(ev) {   
    var id2 = $(this);   
    $.ajax({
        type: $(id2).attr('method'),
        url: $(id2).attr('action'),
        data: $(id2).serialize(),
        success: function(data) {               
        $('.cantidad').val('');
        $('.cartbasket').load(' .cartbasket');
        $('.alert-co').removeClass('hide')
        },
        error: function() {
        $('.alert-inc').removeClass('hide')
        }
    });
    ev.preventDefault();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM