使用js / jQuery实时显示PHP变量的当前值

This might seem easy enough for the lovely experts here at SO :) but I can't find a decent answer/question about this on SO or google. Pls help. :)

How do i display a current value of a php variable in realtime via AJAX/js/jQuery

Basically im trying to do an E-commerce site and I am storing the shopping cart contents using a session and displaying it with an echo statement counting how many contents is currently in the basket, however when they are on a certain product and tried adding it in the cart, the value of the cart doesn't echo the added item until there is a page refresh, so i need something like an AJAX to display the updated value of the session when an item is added without having a page refresh.

Thank you so much.

Here is my code snippet for the cart as a sample:

// Assign shopping cart ($_SESSION['cart']) into variable
$basket = count($_SESSION['cart']);

And for displaying:

<!-- Display contents of the shopping cart -->
<ul id="basket" class="clearfix">
   <li class="top">
      <a href="checkout.php" class="top_link"> 
         <span>Items: <? echo $basket ?></span>
      </a> 
   </li>
</ul>

Thank you so much.. kindly provide a sample code on how to achieve this (either js or jQuery) and would help as well for best practices in dealing with this type of scenario.

First solution (based on your request - BAD IDEA)

get-count-items.php
<?php
    session_start();
    die(count($_SESSION['cart']));
?>

Javascript
<script>
    setInterval(function(){
        $.post('get-count-items.php', {}, function (total_items){
            $('#total-items').html(total_items);
        });
    }, '1000');
</script>

HTML
<ul id="basket" class="clearfix">
    <li class="top">
        <a href="checkout.php" class="top_link"> 
            <span>Items: <span id="total-items"><? echo $basket ?></span></span>
        </a> 
    </li>
</ul>

This javascript will make a request to server at each 1 second.

Second solution (event on button "Add to cart")

add-to-cart.php
<?php
    session_start();
            // code for add to cart...
    die(count($_SESSION['cart']));
?>


Javascript
<script>
    $('.add-to-cart').click(function(){
        $.post('add-to-cart.php', {}, function (total_items){
            $('#total-items').html(items);
        });
        return false;
    });
</script>

HTML
<ul id="basket" class="clearfix">
    <li class="top">
        <a href="checkout.php" class="top_link"> 
            <span>Items: <span id="total-items"><? echo $basket ?></span></span>
        </a> 
    </li>
</ul>

<a href="" class="add-to-cart">Add to cart</>