I try to make a link fire a JavaScript function which fires an ajax call to delete an item.
Like so:
<a class="delete" href="@item.Product.Id">(x)</a>
Clicking the cross carries the id of the product to be deleted. The only reason the href attribute is there is to carry the value.
$(document).ready(function () {
$('.delete').click(function (e) {
e.preventDefault();
var id = $(this).attr("href");
deleteItem(id);
return false;
});
});
Ajax call: as requested:
function deleteItem(id) {
$.ajax({
url: "/Shoppingcart/RemoveItem",
type: "POST",
data: "id=" + id,
cache: false,
error: function (xhr, status, error) {
console.log(xhr, status, error);
},
success: function () {
$.ajax({
url: "/Shoppingcart/Index",
type: "GET",
cache: false,
error: function (xhr, status, error) {
console.log(xhr, status, error);
},
success: function (result) {
success(result);
}
});
}
});
}
The success function is there to get an updated version of the cart. And this actually works just fine. However I get a weird page refresh half way through the cycle.
I click the link.
the page refreshes and the item is not deleted.
I click the link once more.
the page is not refreshed.
the item is deleted.
Why do I have to click two times and what can I do to resolve this?
The most correct answer is: You don't know what the error is, because the page is refreshing before you see the error.
Return false prevents the page from refreshing after a click event, but if the code runs into an error before that point...
So you could try to remove the href
tag and make it an rel (or something else) tag instead. read that and use it for your AJAX call. give the href
a value like #
or #removeItem
.
This will give you the error your craving for.
Hope this helps!