0

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??

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Appereantly, it was a parent problem.. Thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.