1

Our site has a lengthy AJAX function that appends content to the user's cart, which is stored as an array in the usermeta table.

The function looks something like this:

$cart = get_user_meta($userID, 'cart', true);
$cart[] = $newItemID;
update_user_meta($userID, 'cart', $cart);

We're running into a problem where, when the user tries to add multiple items to their cart in rapid succession, the final call to update_user_meta will sometimes overwrite the cart with old data.

From what I understand, this is a race condition which is partly caused by the fact that WordPress stores array data as a serialized string rather than as a set of table rows.

I know that I could just create a cart table and use queries to manage it, but I was hoping that there was a way to do it with the existing get_user_meta/update_user_meta functions.

  • Have you got any additional plugin for handling e-commerce or you're doing the whole thing on your own? – Kumar Apr 24 at 2:54
  • @sven - The plugin is completely in-house. Even though this specific issue is about e-commerce, the question is more of a general one. It could be applied to any situation where update_user_meta is called frequently. – Pikamander2 Apr 24 at 3:00
0

This happens due to the nature of ajax calls - they are asynchronous. When you have a lengthy function (or heavy plugins and slow site loading), several ajax calls are running at the same time, and nobody can predict, which one will get access to db data faster.

Usage of own tables is not a solution in this situation.

The easiest way to solve the problem is to block further adding of a product by Javascript until current ajax is finished.

So, sequence of actions in js should be:

  • by the click on the add to cart button set flag blocking other clicks

  • run ajax

  • in .complete function delete the flag so allowing further add to cart clicks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.