duanrong6802 2013-09-02 22:50
浏览 67
已采纳

单击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>
}
  • 写回答

2条回答 默认 最新

  • dongque8332 2013-09-02 23:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改