PHP Ajax wait for function to finish before user can call it again Server-side

What i have is:

A user has 100 Points on his account. The function will subtract 10 points from his balance. Then the 10 points will go to another User.

The problem is that if the user spams the button 11 times, the other user still gets +10 points, even if the balance is at 0. This happens because the function is executed multiple times at once.

So I basically have the same problem like this question, but i have to handle it server-side. Wait for function to finish before starting again

Example code:

function subtract() {
    $.ajax({
        type: 'POST',
        url: 'verify.php',
        data: {
            'token':token
        },
        complete: function(r) {
            var success = r.responseText;
        }
    });
}

verify.php

$getCurrentBalance; //Points from Database
$subtract = $getCurrentBalance - 10;

updateBalance(); //Update the users balance with subtracted Points

So everything works great, but I have to check on the server side if the function has finished before the user can call it again.

1 answer

  • answered 2018-07-11 03:00 Ggg

    You could consider it more like a comment but I strongly would like to point out that suggestion for client-side solution should not be a good way to solve problem because the client cannot and should not be trusted.

    One way of solving it could be to "lock" the account while a transaction is ongoing. The lock could consist of a Boolean; true for unlocked and false for locked, as an example. The lock itself should be in the database table itself. From your programming you could 'deactivate' the button using css. That way you cover both cosmetic and functional.