I have created a function which makes an ajax request to a PHP file and then adds a product to the basket. This function works as it should on the first click, but on each subsequent click it runs the function again. So for example, on the 2nd click it runs the function twice, on the 3rd click it runs it three times and so on… The problem is reset when the page is refreshed…
Here’s the on click code:
$("#add_123456").click(function () {
$("#add_123456").addClass('added');
var quantity = $("#qty_123456").val();
$('#basket_1').submit(function (event) {
event.preventDefault();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});
});
Here’s the function:
function basket_add(cartID, productID, code, quantity, weight, price) {
var item_add = {"Cart_ID": cartID,
"Product_ID" : productID,
"Code" : code,
"Qty" : quantity,
"Weight" : weight,
"Price" : price
};
$("#basketpop").animate({top: "40px"}, 200);
$.ajax({
url: '/templates/new/includes/ajax/add_to_basket.php',
type: 'POST',
data: item_add,
dataType: "html",
success: function(html){
$('.basket_content').empty().append(html);
$('.basket_content').css("height", "auto");
var item_add = null;
}
});
return false;
};
Don’t think the issue is with the PHP file that is being called.
Cheers
Assuming the
#add_123456button is asubmitbutton, the problem is because you are adding a newsubmit()handler to the form on each click of the button. Instead you only need to add the submit handler once and raise the event on the form on button click. Try this:If you are only submitting via AJAX though, you can remove the need to submit the form at all, like this: