There is a basket of goods, it works using a session, as well as a php handler and a js file that sends Ajax requests to the handler.

So, let's say we have 10 items in the basket. Now I delete them one by one.

If this is done slowly, then everything will go well.

If you click on the crosses quickly, then not all products can be removed (they do not have time) or, if everything is deleted, then the quantity of goods in the basket and the total amount may not be zeroed out.

Why it happens?


Example Ajax request:

//Обновление виджета корзины в шапке function updateCart() { $.post('/wp-admin/admin-ajax.php', { action: 'updateCart' }, function (res) { $('.cart-btn').html(res); } ); } updateCart(); 

Sample PHP handler:

 function updateCart(){ $data = json_decode(stripslashes($_SESSION['cart']), ARRAY_A); // Перебераю массив foreach ($data as $key => $value) { // Узнаю общее количество товара $quantity_product += $value; // Узнаю цену и умножаю на колличество $price_product += get_field('price', $key) * $value; } // Вывожу колличество товара и сумму if(!$data){ echo "Товаров 0 (0) тг."; } else { if($quantity_product == 1) { echo "$quantity_product товар ($price_product) тг."; } elseif($quantity_product > 1) { echo "Товаров: $quantity_product ($price_product) тг."; } } die(); } 
  • And where is the recording of the session variable? - Maxim Stepanov
  • Although, as I understand it, this is meaningless code. In case of an AYAX request, recalculation of the quantity of goods and the amount must be made on the client by means of js after the server successfully responds to the removal of the goods. - Maxim Stepanov

1 answer 1

Answers to multiple requests will not necessarily come in the order in which they are sent.

It is easiest to ban a new request until the previous one has been worked out, although this is far from the best solution. For example:

 var isWaiting; //Обновление виджета корзины в шапке function updateCart() { if (isWaiting) { return; } isWaiting = true; $.post('/wp-admin/admin-ajax.php', { action: 'updateCart' }, function (res) { //Очистить флаг ожидания после успешного выполнения запроса isWaiting = false; $('.cart-btn').html(res); } ).fail(function(res) { //Очистить флаг ожидания при ошибке запроса isWaiting = false; }); } updateCart(); 
  • @ MaksimStepanov For the code that is given, the cause of the errors is named correctly. And this is the right decision, albeit in the forehead. You can offer the best for this code - go ahead, offer. - Sergey Nudnov
  • @MaksimStepanov Your approach to solving the problem is correct. My, for this case - not very. My solution is more applicable when we do not want to execute a certain request, while another, the same is not completed. Only here you lead the discussion ugly. - Sergey Nudnov 11:36 pm
  • Why not use the $ .ajax wrapper with the async: false parameter? - Kirill Korushkin