单击div A时异步更新div B.

I'm working on small ecommerce and I'm trying to update the item count in the cart as soon as an item is added to it.

I'm sure I'm missing one step because unless the page gets refreshed, the cart doesn't get updated.

Div to add item:

<div class="buy_button">
  <h2><a href="#" class="addtocart" id="<?php echo $item_id ?>">Add item</a></h2>
</div>

Div that needs to be updated asynchronously:

<div id="cart">

//SQL query to get count of items in table

<h2><?php echo $item_count ?></h2>
</div>

.

$(function() {
$(".addtocart").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
});

return false;
});
});

Here is ajax_add.php:

if($_POST['id']) {

//SQL query to save item in table 
//SQL query to count items in table

<div id="cart">
//SQL query to get count of items in table
    <h2><?php echo $item_count ?></h2>
</div>
}

First, your syntax is wrong and should be throwing an error in console.

data: info,

you have a trailing comma on the object you are passing to the ajax method.

also, you have no callback function to handle the data. Considering the code you presented, you would update the count as such:

$.ajax({
    type: "POST",
    url: "ajax_add.php",
    data: info,
    success: function (data) {
        $('#cart h2').text($(data).find('#cart h2').text());
    }
});

It would certainly be better to have ajax_add.php return a json object or just the updated count value.

You have to do something with the response from the AJAX call.

$(function() {
    $(".addtocart").click(function(){
        var element = $(this);
        var I = element.attr("id");
        var info = 'id=' + I;
        $.ajax({
            type: "POST",
            url: "ajax_add.php",
            data: info,
            success: function(response) {
                $("#cart").replaceWith(response);
            }
        });
        return false;
    });
});