购物车更新与ajax和PHP

时间:2015-08-21 17:28:25

标签: php jquery ajax

我正在学习如何使用ajax,jquery和php来更新购物车。我发现了这段代码,我试图改编它,但没有成功。问题是,我无法将任何项目添加到购物车,在谷歌搜索后仍然不知道问题出在哪里。

<script>
   $(document).ready(function(){    
    $(".form-item").submit(function(e){
        var form_data = $(this).serialize();
        var button_content = $(this).find('button[type=submit]');
        button_content.html('Adding...'); //Loading button text 

        $.ajax({ //make ajax request to cart_process.php
            url: "../../cart_process.php",
            type: "POST",
            dataType:"json", //expect json value from server
            data: form_data
        }).done(function(data){ //on Ajax success
            $("#cart-info").html(data.items); //total items in cart-info element
            button_content.html('Add to Cart'); //reset button text to original text
            alert("Item added to Cart!"); //alert user
            if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
                $(".cart-box").trigger( "click" ); //trigger click to update the cart box.
            }
        })
        e.preventDefault();
    });

//Show Items in Cart
$( ".cart-box").click(function(e) { //when user clicks on cart box
    e.preventDefault(); 
    $(".shopping-cart-box").fadeIn(); //display cart box
    $("#shopping-cart-results").html('<img src="images/ajax-loader.gif">'); //show loading image
    $("#shopping-cart-results" ).load( "../../cart_process.php", {"load_cart":"1"}); //Make ajax request using jQuery Load() & update results
});

//Close Cart
$( ".close-shopping-cart-box").click(function(e){ //user click on cart    box close link
    e.preventDefault(); 
    $(".shopping-cart-box").fadeOut(); //close cart-box
});

//Remove items from cart
$("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
    e.preventDefault(); 
    var pcode = $(this).attr("data-code"); //get product code
    $(this).parent().fadeOut(); //remove item element from box
    $.getJSON( "../../cart_process.php", {"remove_code":pcode} ,  function(data){ //get Item count from Server
        $("#cart-info").html(data.items); //update Item count in cart-   info
        $(".cart-box").trigger( "click" ); //trigger click on cart-box   to update the items list
    });
});

});

prodotto.php这里我有产品说明,选择数量的表格和将产品添加到购物车的按钮

<?php
require_once("../inc/config.php");
require_once(ROOT_PATH . "inc/database.php");
require_once(ROOT_PATH . "prodotti/prod.php");
require_once(ROOT_PATH . "login/user.php");
sec_session_start();




 if(isset($_GET['sku'])) {
 $sku = intval($_GET['sku']);
 $prodotto = get_product_single($sku);
 }

 if(empty($prodotto)){
 header("Location:" . BASE_URL);
 exit();
 }



 include(ROOT_PATH . "inc/header.php"); 
 include(ROOT_PATH . "inc/side-menu.php");  

try{ 
$results = $db->prepare("SELECT * from prodotti WHERE sku = ?");
$results->bindParam(1,$sku);
$results->execute();

$prodotto = $results->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Nessun prodotto da visualizzare con queste caratteristiche";
die();
} 
?>
   <div id="content" class="large-8 columns round-all" role="main" itemscope itemtype="http://schema.org/LocalBusiness" style="background-color:#eee;padding-right:1em;">
    <div class="row" style="padding-right:1em;">

      <?php
      $categoria = get_category($prodotto['categoria']);

      ?>
      <nav class="breadcrumbs" role="menubar" aria-label="breadcrumbs" itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
        <li role="menuitem"><a href="<?php echo BASE_URL;?>categorie/index.php?sku=<?php echo $categoria['id']; ?>" itemprop="url"><span itemprop=”title”><?php echo $categoria['nome'];?></span></a></li>
        <li role="menuitem" class="current"><span itemprop=”title”><?php echo $prodotto['nome'];?></span></li>
      </nav>
      <a href="#" class="cart-box" id="cart-info" title="View Cart">
 <?php 
if(isset($_SESSION["products"])){
 echo count($_SESSION["products"]); 
}else{
echo 0; 
}
?>

<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
 <h3>Your Shopping Cart</h3>
 <div id="shopping-cart-results">
 </div>
 </div>
      <?php

          echo '<li role="menuitem" style="list-style-type:none;">


                  <div class="large-12 columns" style="background-color:#fff;" itemscope itemtype="http://schema.org/Product">
                    <div class="small-1 medium-2 large-4 columns" style="border:10px #eee solid">
                    <span itemprop ="image"><img src="' . BASE_URL . 'img/profumo-hugo-boss.jpg";/></span>
                    </div>
                    <div class="small-1 medium-4 large-8 columns" >
                    <span itemprop="name"><h3>'.$prodotto['nome'].'</h3></span>
                    <h6>Codice: ' . $prodotto['sku'] . '</h6>
                    <span itemprop="price"><h6>Prezzo: <span style="color:red;font-weight:bold;";>' . $prodotto['prezzo'] . '<span itemprop="priceCurrency">€</span></span></h6></span>
                    <span itemprop="description"><p>'.$prodotto['descrizione'].'</p></span>';?>

                    <form class="form-item">
                               <div class="small-1 medium-2 large-4">
                                    <label for="quantita">Quantità</label>

                                <select name="quantita" id="quantita">
                                  <option value="1">1 </option>
                                  <option value="2">2 </option>
                                  <option value="3">3 </option>
                                  <option value="4">4 </option>
                                  <option value="5">5 </option>
                                  <option value="6">6 </option>
                                  <option value="7">7 </option>
                                  <option value="8">8 </option>
                                  <option value="9">9 </option>
                                  <option value="10">10 </option>
                                </select> 
                              </div>
                              <div class="small-1 medium-2 large-4">
                                <input type="hidden" name="sku" value="<?php echo $prodotto['sku'];?>"/>
                                <input type="hidden" name="id_sessione" value="<?php echo $_SESSION['id'];?>"/>
                                <input type="submit" value="Aggiungi al carrello" class="button" name="submit">

                                </div>
                                </form>


                    </div>
                  </div>

                </li>
    </div>
   </div>
  </div>
</div>
   

Cart_process.php

include_once("../inc/config.php");
sec_session_start(); 

############# add products to session #########################
if(isset($_POST["sku"]))
{
foreach($_POST as $key => $value){
    $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);      //create a new product array 
}

//we need to get product name and price from database.
$statement = $db->prepare("SELECT nome, sku FROM prodotti WHERE sku=?    LIMIT 1");
$statement->bindParam(1, $new_product['sku']);
$statement->execute();

$prodotto = $statement-fetch(PDO::FETCH_ASSOC);


while($prodotto){ 
    $new_product["nome"] = $prodotto['nome']; //fetch product name from database
    $new_product["sku"] = $prodotto['sku'];  //fetch product sku from database

    if(isset($_SESSION["products"])){  //if session var already exist
        if(isset($_SESSION["products"][$new_product['sku']])) //check item exist in products array
        {
            unset($_SESSION["products"][$new_product['sku']]); //unset old item
        }           
    }

    $_SESSION["products"][$new_product['sku']] = $new_product;  //update products with new item array   
}

$total_items = count($_SESSION["products"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json 

}

################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{

if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){    //if we have session variable
    $cart_box = '<ul class="cart-products-loaded">';
    $total = 0;
    foreach($_SESSION["products"] as $product){ //loop though items and prepare html content

        //set variables to use them in HTML content below
        $product_name = $product["nome"]; 
        /*$product_price = $product["product_price"];
        */$product_code = $product["sku"];/*
        $product_qty = $product["product_qty"];
        $product_color = $product["product_color"];
        $product_size = $product["product_size"];
        */
        $cart_box .=  "<li> $product_name <a href=\"#\" class=\"remove-item\" data-code=\"$product_code\">&times;</a></li>";
        //$subtotal = ($product_price * $product_qty);
        //$total = ($total + $subtotal);
    }
    $cart_box .= "</ul>";
    //$cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u><a href="view_cart.php" title="Review Cart and Check-Out">Check-out</a></u></div>';
    die($cart_box); //exit and output content
    }else{
    die("Your Cart is empty"); //we have empty cart
   }
  }

  ################# remove item from shopping cart ################
  if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
  {
  $product_code   = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove

if(isset($_SESSION["products"][$product_code]))
{
    unset($_SESSION["products"][$product_code]);
}

$total_items = count($_SESSION["products"]);
die(json_encode(array('items'=>$total_items)));
}

1 个答案:

答案 0 :(得分:0)

从评论中的讨论开始,我将使用来自database的示例数据发布代码的功能行为,因为您希望它是动态的。

  

由于这是出于学习目的,我已经使用了一些msql_准备好的语句。 (两者都在不同的文件中)请注意 msql _   我不推荐使用它。

在开始之前,我假设您已经将所有必需的文件下载并保存在正确的路径中,并使用任一方法(文件系统/直接存储到数据库)来获取图像,但我使用了文件系统行为。现在,数据库中使用了三个表:

1)category表格,列如下:

  • CAT_ID
  • cat_name

2)item表,其中包含以下列:

  • ITEM_ID
  • ITEM_NAME
  • item_quantity
  • item_size
  • cat_id(来自category表格的FK)
  • item_color

3)products_list表包含以下列:

  • id(AI,PK)
  • PRODUCT_NAME
  • product_desc
  • PRODUCT_CODE
  • product_image
  • item_id(来自item表格的FK)
  • PRODUCT_PRICE
  • product_discount

现在,从第一页开始。

  

的index.php

<?php
session_start(); //start session
include("config.php"); //include config file
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>

<script>
$(document).ready(function(){   
        $(".form-item").submit(function(e){
            var form_data = $(this).serialize();
            var button_content = $(this).find('button[type=submit]');
            button_content.html('Adding...');  

            $.ajax({ 
                url: "cart_process.php",
                type: "POST",
                dataType:"json", 
                data: form_data
            }).done(function(data){ 
                $("#cart-info").html(data.items); 
                button_content.html('Add to Cart'); 
                alert("Item added to Cart!"); 
                if($(".shopping-cart-box").css("display") == "block"){ 
                    $(".cart-box").trigger( "click" ); 
                }
            })
            e.preventDefault();
        });

//Show Items in Cart
    $( ".cart-box").click(function(e) { 
        e.preventDefault(); 
        $(".shopping-cart-box").fadeIn(); 
        $("#shopping-cart-results").html('<img src="images/ajax-loader.gif">'); 
        $("#shopping-cart-results" ).load( "cart_process.php", {"load_cart":"1"}); 
    });

//Close Cart
    $( ".close-shopping-cart-box").click(function(e){ 
        e.preventDefault(); 
        $(".shopping-cart-box").fadeOut(); 
    });


//Remove items from cart
    $("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
        e.preventDefault(); 
        var pcode = $(this).attr("data-code"); 
        $(this).parent().fadeOut(); 
        $.getJSON( "cart_process.php", {"remove_code":pcode} , function(data){ 
            $("#cart-info").html(data.items); 
            $(".cart-box").trigger( "click" );
        });
    });

});
</script>

<?php
$que = "SELECT * FROM category";
$run = mysql_query($que);
$j = 0;
while($row = mysql_fetch_array($run))
{
    $cat_idd[$j] = $row['cat_id'];
    $cat_namee[$j] = $row['cat_name'];
$j++;
}

for($i = 0;  $i < count($cat_idd);  $i++)
    {
        $que2 = "SELECT * FROM item WHERE cat_id = '$cat_idd[$i]' ";
        $result = mysql_query($que2);
        $run = mysql_num_rows($result);

        echo"<table>";
        echo"<th id = 'hidden'></th>";
        echo"<tr>";
        echo"<td id = 'side' width = '110'>";
        echo "&nbsp;&nbsp;"."<a href='index.php?id=$cat_idd[$i]' style = 'text-decoration: none;' >".$cat_namee[$i]." (".$run.")</a><br><br>";
        echo "</td>";
        echo "</tr>";
        echo "</table>";
    }


require('config.php');
if(isset($_GET['id']))
{
    $cat_id = $_GET['id'];
    $que = "SELECT * FROM item WHERE cat_id = '$cat_id'";
    $run = mysql_query($que);
?>
<form class="form-item">

<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php 
if(isset($_SESSION["products"])){   
    echo count($_SESSION["products"]); 
}else{
    echo 0; 
}
?>
</a>

<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
<h3>Your Shopping Cart</h3>
    <div id="shopping-cart-results">
    </div>
</div>

<?php

    while($row = mysql_fetch_array($run))
    {
        $i_id = $row['item_id'];
        $i_name = $row['item_name'];
        $i_quantity = $row['item_quantity'];
        $i_size = $row['item_size'];
        $i_color = $row['item_color'];
        ?>


<?php
$query3 = "SELECT product_name, product_price, product_desc, product_code, product_image, product_discount FROM products_list WHERE item_id = '$i_id' ";
$run3 = mysql_query($query3);


while($row3 = mysql_fetch_array($run3)) {
    ?>

    <ul class="products-wrp">
<li>
<form class="form-item">
<h4><?php echo $row3['product_name']; ?></h4>
<div><img src="images/<?php echo $row3['product_image']; ?>"height = "150" width = "180"></div>
<?php echo "Availabe Quantity: " . $i_quantity . "<br>"; ?>
<?php 
if($row3['product_discount'] == 0)
{
echo "Rs. " . $row3['product_price']; 
}
else
{
echo "NOW ". $row3['product_discount'] . "% OFF!";
echo '<div>Rs. <span style = "text-decoration: line-through;">'.$row3['product_price'].'</span></div>';
$discount = ((($row3['product_discount'])/100) * $row3['product_price']);
$f_price = ($row3['product_price'] - $discount);
echo "Rs. ". $f_price . ".00" ;
}
?>

<div class="item-box">
    <div>
    Color :

    <?php 
$arr = $row["item_color"];  
    $exp = explode("," , $arr);
    echo "<select name='product_color'>";
foreach($exp as $key=>$val) {
    echo "<option value='" . $val . "'>" . $val . "</option>";
}
echo "</select>";
?>
<!--    <select name="product_color">
    <option value="Red">Red</option>
    <option value="Blue">Blue</option>
    <option value="Orange">Orange</option>
    </select>
-->
    </div>

    <div>
    Qty :
    <input type = "number" name = "product_qty" min = "1" max = "<?php echo $i_quantity; ?>" 
    value = "1" title = "Please Enter the Numbers Below Available Quantity Only."> 
<!--
    <select name="product_qty">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    </select>
    </div>
--> 
    <div>
    Size :  

<?php 
$arr = $row["item_size"];  
    $exp = explode("," , $arr);
    echo "<select name='product_size'>";
foreach($exp as $key=>$val) {
    echo "<option value='" . $val . "'>" . $val . "</option>";
}
echo "</select>";
?>  
    <input name="product_code" type="hidden" value="<?php echo $row3['product_code']; ?>">
    <button type="submit">Add to Cart</button>
</div>
</form>
</li>
</ul>
</div>

<?php  }  } }?>
</body>
</html>

现在点击“添加到购物车”的第一件事就是对cart_process.php的ajax请求,其中json值应该返回。

  

cart_process.php

<?php
session_start(); 
$db_username        = 'root'; 
$db_password        = '';
$db_name            = 'yourdbnamehere'; 
$db_host            = 'localhost';

$currency           = 'Rs. ';
$shipping_cost      = 500; 
$taxes              = array( 
                            'VAT' => 12, 
                            'Service Tax' => 5,
                            'Other Tax' => 10
                            );

$mysqli_conn = new mysqli($db_host, $db_username, $db_password,$db_name); 
if ($mysqli_conn->connect_error) {
    die('Error : ('. $mysqli_conn->connect_errno .') '. $mysqli_conn->connect_error);

// add products to session 
    if(isset($_POST["product_code"]))
    {
        foreach($_POST as $key => $value){
            $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
        }

        $statement = $mysqli_conn->prepare("SELECT product_name, product_price, product_discount FROM products_list WHERE product_code=? LIMIT 1");
        $statement->bind_param('s', $new_product['product_code']);
        $statement->execute();
        $statement->bind_result($product_name, $product_price, $product_discount);


        while($statement->fetch()){ 
            $new_product["product_name"] = $product_name; 
            $new_product["product_price"] = $product_price; 
            $new_product["product_discount"] = $product_discount;  

            if($product_discount == 0)
            {
                $product_price = $product_price;
            }
            else
            {
                $discount = (($product_discount/100) * $product_price);
                $product_price = $product_price - $discount;
            }

            if(isset($_SESSION["products"])){  
                if(isset($_SESSION["products"][$new_product['product_code']])) 
                {
                    unset($_SESSION["products"][$new_product['product_code']]);
            }
            $_SESSION["products"][$new_product['product_code']] = $new_product;     
        }

        $total_items = count($_SESSION["products"]); 
        die(json_encode(array('items'=>$total_items)));  

    }

    // list products in cart 
    if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
    {

        if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ 
            $cart_box = '<ul class="cart-products-loaded">';
            $total = 0;
            foreach($_SESSION["products"] as $product){ 

                $product_name = $product["product_name"]; 
                $product_price = $product["product_price"];
                $product_code = $product["product_code"];
                $product_qty = $product["product_qty"];
                $product_color = $product["product_color"];
                $product_size = $product["product_size"];
                $product_discount = $product["product_discount"];

            if($product_discount == 0)
            {
                $product_price = $product_price;
            }
            else
            {
                $discount = (($product_discount/100) * $product_price);
                $product_price = $product_price - $discount;
            }

                $cart_box .=  "<li> $product_name (Qty : $product_qty | $product_color  | $product_size ) &mdash; $currency ".sprintf("%01.2f", ($product_price * $product_qty)). " <a href=\"#\" class=\"remove-item\" data-code=\"$product_code\">&times;</a></li>";
                $subtotal = ($product_price * $product_qty);
                $total = ($total + $subtotal);
            }
            $cart_box .= "</ul>";
            $cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u><a href="view_cart.php" title="Review Cart and Check-Out">Check-out</a></u></div>';
            die($cart_box); 
        }else{
            die("Your Cart is empty"); 
        }
    }
    // remove item from shopping cart
    if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
    {
        $product_code   = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); 

        if(isset($_SESSION["products"][$product_code]))
        {
            unset($_SESSION["products"][$product_code]);
        }

        $total_items = count($_SESSION["products"]);
        die(json_encode(array('items'=>$total_items)));
    }

当你点击"Check-out"中的add-to-cart box时,就会出现这个部分。它将您带到另一个页面(在我们的例子中是最后一个),您可以在其中看到您购买的所有产品。

  

view_cart.php

<?php
session_start();
include("config.inc.php"); //one written above in cart_process.php
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Review Your Cart Before Buying</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<body>
<?php 
if(isset($_COOKIE['user']))
{  
$last = $_COOKIE['user']; 
echo '<a href = "signout.php" id = "btn" name ="signout">SignOut</a>';
echo "Logged in: ". $last . "<br><br>"; 


echo '<h3 style="text-align:center">Review Your Cart Before Buying</h3>';

if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
    $total          = 0;
    $list_tax       = '';
    $cart_box       = '<ul class="view-cart">';

    foreach($_SESSION["products"] as $product){ 
        $product_name = $product["product_name"];
        $product_qty = $product["product_qty"];
        $product_price = $product["product_price"];
        $product_code = $product["product_code"];
        $product_color = $product["product_color"];
        $product_size = $product["product_size"];
        $product_discount = $product["product_discount"];

        if($product_discount == 0)
        {
            $product_price = $product_price;
        }
        else
        {
            $discount = (($product_discount/100) * $product_price);
            $product_price = $product_price - $discount;
        }

        $item_price     = sprintf("%01.2f",($product_price * $product_qty));  // price x qty = total item price

        $cart_box       .=  "<li> $product_code &ndash;  $product_name (Qty : $product_qty | $product_color | $product_size) <span> $currency$item_price </span></li>";

        $subtotal       = ($product_price * $product_qty); 
        $total          = ($total + $subtotal); 
    }

    $grand_total = $total + $shipping_cost; 

    foreach($taxes as $key => $value){ 
            $tax_amount     = round($total * ($value / 100));
            $tax_item[$key] = $tax_amount;
            $grand_total    = $grand_total + $tax_amount; 
    }

    foreach($tax_item as $key => $value){ 
        $list_tax .= $key. ' '. $currency. sprintf("%01.2f", $value).'<br />';
    }

    $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';

    $cart_box .= "<li class=\"view-cart-total\">$shipping_cost  $list_tax <hr>Payable Amount : $currency ".sprintf("%01.2f", $grand_total)."</li>";
    $cart_box .= "</ul>";

    echo $cart_box;
    echo '<a href = "confirmpurchase.php?conf_pur=check" style = "text-decoration: none; float: right;">Confirm Purchase</a>';
}else{
    echo "Your Cart is empty";
}
}
else
    if(!isset($_COOKIE['user']))
     {
         echo "You must be logged in to purchase!<br>";
         echo '<a href = "login.php" id = "btn" name ="login">Login</a>';

    } 

?>

</body>
</html>

我在此处发布之前已经运行并检查了所有处理,因此它应该可以帮助您了解确切的行为和移动方式。

干杯。