1

just hope this is not a stupid question.

I have an eCommerce site and when user adds an item to cart. On top of the page I have this function which count the array and then shows the user how many item is in cart.

Then I am store the total cart price in a session to show show on top of the page as well.

I am using Jquery to add an item to cart but the problem is you have to refresh the page to so that you can see the total cart item and total cart price(On top of the page. Not the cart page. So don't get it mix it).

I used location.reload(); to reload in the Jquery but this refresh the own page.

To show the number of item the user have in cart I did count

<?php echo count($_SESSION["cart_array"])?>

and for the total item price echo the session

<?php echo $_SESSION['smallcart'];?>

How can I use PHP or any other form to refresh the count and the smallcart session without refresh the page.

Those those are in my pageheader.php

which I <?php include realpath(dirname(__FILE__)."/../../pageheader.php"); ?>

is they a way i can refresh the pageheader.php without refresh the page body.

4

1 回答 1

1

您可以使用 ajax 来执行此操作,如下例所示。首先,我们需要一个 php 文件来创建这些会话并与 ajax 通信。让我们调用这个文件ajax_cart.php。其中可能有以下代码。

    $new_cart_item=$_REQUEST['new_cart_item'];
$new_total=$_REQUEST['new_total'];
$cart_array=array();
//for cart arrays
$item_count=0;
if(isset($_SESSION['cart_array'])){
$cart_array=$_SESSION['cart_array'];
$cart_array[]=$_REQUEST['new_cart_item'];
$_SESSION['cart_array']=$cart_array;
$item_count=count($_SESSION["cart_array"]);
else{
$cart_array[]=$_REQUEST['new_cart_item'];
$_SESSION['cart_array']=$cart_array;
$item_count=count($_SESSION["cart_array"]);
}

//for smart cart
$total_price=0;

$_SESSION['smartcart']=$_REQUEST['new_total'];
$total_price=$_SESSION['smartcart'];
$data='{"cartcount":"'.$item_count.'","totalprice":"'.$total_price.'"}';
echo $data;

然后我们可以添加 ajax 来更新并从该文件中获取结果。从以下代码。

//ajax side
function my_ajax(url,data,method,datatype){
    $.ajax({
    type: method,
    url: url,
    data: data,
    dataType: datatype,
    success: function(data) {
    ajaxResultHandler(data,datatype);
    },
    error: function(error, status, desc) {
        console.log(error);

    }
});
}

function ajaxResultHandler(data,datatype){
//here you can put any function to use the given data
var cart_count=data.cartcount;
var total_price=data.totalprice;
$("div.cart_count").html(cart_count); //your element you display item count
$("div.total_price").html(total_price); //your element you display total price.
}

下面是那个ajax函数的用法。

$('.add_to_cart').live("click",function(e) {
    e.preventDefault();

    //get required data from elements or form. perform addation of price.
    var total_price=0; //put calculated new total price
    var added_item=""; //put the new added item
    //call the ajax function
    my_ajax("ajax_cart.php",{"new_total":total_price,"new_cart_item":added_item},"post","json");
    });

试试这个方法,希望它能解决你的问题。

于 2013-08-27T00:16:01.057 回答