AJAX / PHP购物车,无法正常工作

时间:2014-05-19 13:19:59

标签: php jquery ajax

我在构建购物车时遇到了一些问题。

我没有多次点击添加按钮来更改数量,而是想直接在输入中更改它。它运作良好,但当你删除购物车中的一个项目时,所有其他项目的价格将被设置为零,我不知道为什么会发生这种情况。

我正在使用的购物车是PHP / SQL和AJAX。

到目前为止,这是我的代码:

PHP:

<?php

// This document contains the AJAX generated for the building-cart
/////////////////////////////////////////////////////////////////

// Clear Cache and include config.php
include("includes/config.php");
// Start Session
session_start();
?>
<?php

$product_id = $_GET['id']; //the product id from the URL 
$action = $_GET['action']; //the action from the URL
$quantity = $_GET['quantity']; //the action from the URL 

// if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
    die("Error. Product Doesn't Exist");
}

// decide what to do 
switch($action) {

    case "add":

    //add one to the quantity of the product with id $product_id 
    if($_SESSION['cart'][$product_id] < 1) { $_SESSION['cart'][$product_id]++; }

    break;

    case "remove":
        $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id 
        if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. 
    break;

    case "empty":
        unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
    break;

}

?>
<?php 

//if the cart isn't empty show the cart
if($_SESSION['cart']) {

    echo '<ul id="cart-items">'."\n";

    //iterate through the cart, the $product_id is the key and $quantity is the value
    foreach($_SESSION['cart'] as $product_id => $quantity) { 

        //get the name, description and price from the database - this will depend on your database implementation.
        //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
         $result = mysql_query("SELECT * FROM single_partners WHERE single_id = $product_id");

        //Only display the row if there is a product (though there should always be as we have already checked)
        if(mysql_num_rows($result) > 0) {

            if($test = mysql_fetch_array($result)) {
                $partner_id = $test['partner_id'];
                $partner_price = $test['price'];

                $line_cost = $partner_price * quantity; //work out the line cost
                $total = $total + $line_cost; //add to the total cost
            }   

            // Get partner name
            $get_partner_name = mysql_query("SELECT * FROM partners WHERE partner_id='$partner_id'");
            if($partner_name = mysql_fetch_array($get_partner_name)) {

                $name = $partner_name['name'];
                $logo = $partner_name['logo'];
                $type = $partner_name['type'];
                $logo_dir = "media/partners/build/color/";

            }

            echo '<li>'."\n";
            echo '<div class="logo" style="background-image: url('.$logo_dir.$logo.')">'."\n";
            echo '</div>'."\n";
            echo '<div class="details">'."\n";
            echo '<span class="name">'.$name.'</span>'."\n";
            echo '<span class="details">Detaljer</span>'."\n";
            echo '</div>'."\n";
            echo '<div class="price"><input name="partner" type="hidden" value="'.$product_id.'" /><span class="remove-button"></span>'."\n";
            echo '<span class="price">'.number_format((float)$line_cost, 2, ',', '').'</span>'."\n";
            echo '</div>'."\n";
            echo '</li>'."\n";
        }
    }
    echo '<div class="footer">'."\n";
    echo '<span class="empty-button">Tøm</span>'."\n";
    echo '<span class="total-price">'.number_format((float)$total, 2, ',', '').'</span>'."\n";
    echo '</div>'."\n";
    //show the total
//    echo "<tr>";
//    echo "<td colspan=\"2\" align=\"right\">Total</td>";
//    echo "<td align=\"right\">$total</td>";
//    echo "</tr>";
//
//    //show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
//    echo "<tr>";
//    echo "<td colspan=\"3\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>";
//    echo "</tr>"; 
    echo '</ul>'."\n";



}else{
//otherwise tell the user they have no items in their cart
    //echo "You have no items in your shopping cart.";

}

//function to check if a product exists
function productExists($product_id) {
    //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
    $sql = mysql_query("SELECT * FROM single_partners WHERE single_id = $product_id");

    return mysql_num_rows($sql) > 0;
}
?>

AJAX:

// Load building cart, when adding items
$(document).on('click', 'input[type=button].add-button', function() {

    // AJAX - Define data to send
    var actiontype = "add";
        productid = $('input[name="address"]').val();
        quantity = $('input[name="qun"]').val();
    var data = "action="+ actiontype + "&id="+ productid + "&quantity="+ quantity;
    $.ajax({
        url: 'buildingcart.php',
        data: data,
        success:function(result) {  
            // Show result
            $('#building-cart .content').html(result);
        }
    });
});

// Load building cart, when adding items
$(document).on('click', '.remove-button', function() {

    // AJAX - Define data to send
    var actiontype = "remove";
        productid = $(this).parent().find('input[name="partner"]').val();

    var data = "action="+ actiontype + "&id="+ productid;
    $.ajax({
        url: 'buildingcart.php',
        data: data,
        success:function(result) {  
            // Show result
            $('#building-cart .content').html(result);
        }
    });
});

// Load building cart, when adding items
$(document).on('click', '.empty-button', function() {

    // AJAX - Define data to send
    var actiontype = "empty";

    var data = "action="+ actiontype;
    $.ajax({
        url: 'buildingcart.php',
        data: data,
        success:function(result) {  
            // Show result
            $('#building-cart .content').html(result);
        }
    });
});

我尝试过更改

foreach($_SESSION['cart'] as $product_id => $quantity)

foreach($_SESSION['cart'] as $product_id)

没有运气。

1 个答案:

答案 0 :(得分:3)

你在这一行忘记了一个$符号

$ line_cost = $ partner_price *数量; //计算出行费用

应该是

$ line_cost = $ partner_price * $ quantity; //计算出行费用

编辑: 您也可能希望优化代码,只能选择一个sql:

//if the cart isn't empty show the cart
if($_SESSION['cart']) {
    echo '<ul id="cart-items">'."\n";

    $productIds = implode(",", array_keys($_SESSION['cart']));

    $sql = "
        SELECT
            single_partners.single_id AS product_id,
            single_partners.partner_id,
            single_partners.price,
            partners.name,
            partners.logo,
            partners.type

        FROM single_partners
        INNER JOIN partners
            ON partners.partner_id = single_partners.partner_id
        WHERE single_id IN ({$productIds})
    ";
    $result = mysql_query($sql);

    $logo_dir = "media/partners/build/color/";
    if(mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_array($result)) {
            $product_id = $row['product_id'];
            $partner_id = $row['partner_id'];
            $partner_price = $row['price'];
            $name = $row['name'];   
            $logo = $row['logo'];
            $type = $row['type'];
            $quantity = $_SESSION['cart'][$product_id];

            $line_cost = $partner_price * $quantity; //work out the line cost
            $total = $total + $line_cost; //add to the total cost        

            echo '<li>'."\n";
            echo '<div class="logo" style="background-image: url('.$logo_dir.$logo.')">'."\n";
            echo '</div>'."\n";
            echo '<div class="details">'."\n";
            echo '<span class="name">'.$name.'</span>'."\n";
            echo '<span class="details">Detaljer</span>'."\n";
            echo '</div>'."\n";
            echo '<div class="price"><input name="partner" type="hidden" value="'.$product_id.'" /><span class="remove-button"></span>'."\n";
            echo '<span class="price">'.number_format((float)$line_cost, 2, ',', '').'</span>'."\n";
            echo '</div>'."\n";
            echo '</li>'."\n";
        }
    }

    echo '</ul>'."\n";
}
else{
    //otherwise tell the user they have no items in their cart
    //echo "You have no items in your shopping cart.";
}