用ajax和php更新购物车

I'm learning how can i use ajax, jquery and php to update a cart. I found this code and i'm trying to adapt it, but without success. The problem is that i can't add any item to the cart and after a search on google still don't understand where is the problem.

<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 Here i have the description of the product, the form to select quantity and the button to add the product to the cart

<?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)));
}
查看全部
weixin_33712987
weixin_33712987
2015/08/21 17:28
  • php
  • ajax
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信

1个回复