Categories: php, jquery, ajax

Updating the quantity of a product with AJAX has a problem

1 answer

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;   }); ```  

All answers to this question, which has the identifier 61236064

The best answer:
$('.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').

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type com.google.firebase.iid.zzav is referenced as an interface from com.google.firebase.messaging.zzd”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data