user9771053
user9771053

Reputation:

Updating the quantity of a product with AJAX has a problem

I have a weird problem with using AJAX for the quantity increase of products.

This problem only exists with having more than 1 product on the same cart page.

Let's say there are 2 products. And the product order is ordered by product ID high to low.

If I increase the quantity of the first product in the list it will succeed to increase the quantity. If I then increase the second product quantity it will succeed to increase.

But if I choose the second product to begin with and increase the quantity it doesn't work, the alert then shows still the old quantity(see Jquery AJAX code).

The same happens when I have 3 products etc.

The quantity only updates if I change the quantity from UP to DOWN the list so from the HIGHEST ID to the lower ID.

I don't understand why it behaves like that and I tried a lot but nothing helped.

Can someone explain to me why the code behaves like this and how this can be fixed?

PHP update_quantity.php

<?php
session_start();
include('config/database_connection.php');
// get the product id
echo $id = isset($_GET['id']) ? $_GET['id'] : 1;
echo $quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;

// remove the item from the array
unset($_SESSION['cart'][$id]);

// add the item with updated quantity
$_SESSION['cart'][$id]=array(
    'quantity'=>$quantity
);

?>

cart.php where quantity can get updated

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);
       echo "<form class='update-quantity-form'>";
       echo "<div class='product-id' style='display:none;'>{$id}</div>";
       echo "<div class='input-group'>";
       echo "<input type='number' name='quantity' value='{$quantity}' class='form-control cart-quantity' min='1' />";
      echo "<span class='input-group-btn changeUpdateButton'>";
      echo "<button href='{$id}' class='btn update-quantity' type='submit'>Update</button>";
       echo "</span>";
        echo "</div>";
       echo "</form>";
}

Jquery AJAX update quantity

 $(document).ready(function(){
//Add to cart PRODUCT selected code
  $(".update-quantity").click(function(e){
        var id = $(this).attr("href");
        var quantity = $('.update-quantity-form').find('.cart-quantity').val();
                $.ajax({
          url: "update_quantity.php",
          type: "GET", //send it through get method
          data: {
            id: id,
            quantity: quantity,
          },
          success: function(response) {
                        alert(response);
          },
          error: function(xhr) {
            //Do Something to handle error
          }
        });
    });
 });

Code with what I used BEFORE using Jquery AJAX, which works

    // update quantity button listener
$('.update-quantity-form').on('submit', function(){

    // get basic information for updating the cart
    var id = $(this).find('.product-id').text();
    var quantity = $(this).find('.cart-quantity').val();

    // redirect to update_quantity.php, with parameter values to process the request
    window.location.href = "update_quantity.php?id=" + id + "&quantity=" + quantity;
    return false;
  });
```

Upvotes: 0

Views: 1193

Answers (1)

Barmar
Barmar

Reputation: 782594

$('.update-quantity-form').find('.cart-quantity').val()

will get the quantity from the first form on the page, not the form that the user clicked in. Use

$(this).closest('.update-quantity-form').find('.cart-quantity').val()

to get the quantity from the same form.

Also, you shouldn't use non-standard attributes in HTML elements. href is not valid in <button>, it's only used for <a>. To add application-specific data to elements, use data-XXX attributes, which can be accessed in jQuery with the .data() method.

So change it to:

echo "<button data-id='{$id}' class='btn update-quantity' type='submit'>Update</button>";

and then use $(this).data('id') instead of $(this).attr('href').

Upvotes: 1

Related Questions