简体   繁体   English

如何使用 ajax 将产品添加到购物车?

[英]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.我正在创建一个电子商务 web 页面,它几乎完成了,但我注意到在将产品添加到购物车时,它会重定向到 PC 上产品部分的开头(即产品 1)几乎不会影响任何事情,因为产品可以显示在整个屏幕上,但是如果您在移动设备上并且添加了 1 个非常糟糕的产品,这将非常乏味,起初我尝试添加重定向到产品 id 在表单的操作中,因此避免在开始时进行,但是这种重定向很糟糕,可能会让客户头晕目眩。 Then try to do it with ajax, I already reviewed other posts and I even saw tutorials but none of them work for me.然后尝试用 ajax 来做,我已经查看了其他帖子,我什至看到了教程,但它们都不适合我。 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): productadd(所有产品的表格):

<?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): addCart.php(添加产品的功能):

    <?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.问题是表单成功并执行我成功执行的操作success: function(data)但产品未添加到购物车。 And chrome console doesnt show any error.并且 chrome 控制台没有显示任何错误。

i´ve already done it.我已经做到了。 If anyone wanna know, here is the ajax code:如果有人想知道,这里是 ajax 代码:

$('.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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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