Reputation: 27387
I create add to cart functionality with ajax. My problem is that when I add new item to my cart, and then want to delete its, I can't. But after postbacke of page, I can remove item. I looked at questions about my problem, but can't find solution. My codes as follow:
/*============ Add item to dropdown cart ========*/
$(function () {
$("a.cart").click(function () {
var item = $(this).attr("id");
$.ajax({
url: "/Home/AddItemToCart",
data: { "itemId": item },
dataType: "json",
type: "POST",
success: function (data) {
if (typeof data.thumb != "undefined") {
// append new item to cart place
}
}
});
});
});
/*============ delete item from dropdown cart ========*/
$(function () {
$('#mainNav #cart div.cart_content ul li').find('a.remove_item').on('click',
function (e) {
e.preventDefault();
$(this).parents('li')
.animate({ "opacity": "hide" }, "slow");
var item = $(this).attr("id");
var which = "shop";
$.ajax({
url: "/Home/DeleteItemFromCart",
data: { "itemId": item, "which": which },
dataType: "json",
type: "POST",
success: function (data) {
// removing this item from cart place
}
});
}
);
});
/*======= end it =========*/
Upvotes: 0
Views: 2559
Reputation: 1427
Without adding more relevant code, you're reducing the likelihood of getting spot-on answers. With that in mind, I'm guessing that you're not attaching the same, if any, click event handler (code) to newly added items in the 'AddItemToCart' Ajax success
callback. The only elements that will trigger the event handler are the ones that already existed in the DOM at the time when the event handler was registered, i.e. on DOM ready.
While you have the option of refactoring the code to unbind and re-attach the click event handler to all matched elements on the page (directly bound), it would be better to change it into a delegated event handler by passing a selector argument when calling on()
:
$('#mainNav #cart div.cart_content ul li').on('click', 'a.remove_item', function() {
...
});
Upvotes: 1