Reputation: 1231
I have a very strange problem with my ajax requests. I have a code, that increases the quantity of products by one every time I press a button. The code kinda works but I have a problem. When I press the button I am not getting one request, but 4 at the same time! I have no idea how is that even working, but it happens.
So instead of increasing the products by 1 and finishing it increases by 1 four times!!!
Its a simple script:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add/quantity',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
document.location.reload(true);
}
}
});
});
});
and the controller:
public function addQuantityAction( Request $request ) {
$response = new JsonResponse();
$requestData = $request->request->all();
$productid = $requestData['product'];
$quantity = $requestData['quantity'];
/** logic*/
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('MpShopBundle:Product')->find($productid);
$qtyAvailable = $product->getStock();
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
if ( $qtyAvailable > $cart[ $productid ] ) {
$cart[ $productid ] = $cart[ $productid ] + 1;
$response->setData(array('success'=>true,'message'=>'Qunatity increased'));
$session->set('cart', $cart);
} else {
$response->setData(array('success'=>false,'message'=>'Out of stock'));
}
return $response;
}
Why is that even happening??
Upvotes: 0
Views: 57
Reputation: 773
This is because you have multiple listeners to the click event. It's a javascript issue, for sure.
You can tryt this:
$(document).ready(function () {
$(document).off('click', '.add');
$(document).on('click', '.add', function (e) {
Maybe if there is any parent with the same listener, it can happened too. You can use e.stopPropagation(); to avoid it
I hope it helps.
Upvotes: 1