Search code examples
phphtmljqueryforms

PHP $_POST variable not set after using jQuery to disable pressed button and change its text


I have PHP code with several buttons in one form (for simplicity only two buttons in this case). After the button is pressed, the server may take few seconds to process time-complex stuff (i.e. external API calls - not included in the example bellow). I am looking for the simplest solution to achieve the following after the button is pressed:

  • prevent multiple form submission with making pressed button disabled and its text changed to 'Please wait...',
  • after the form is submitted (important: the same PHP page must be loaded) the $_POST variable should be set and become readable in PHP to determine which of the buttons have been clicked.

I have the following code, which disable pressed button and change its text successfully but the PHP $_POST variable is not set somehow:

$(document).ready(function() {
  $('button[type="submit"]').click(function() {
    // Disable the clicked button and change its text
    var buttonText = $(this).text();
    $(this).prop('disabled', true);
    $(this).text('Please wait...');

    // Submit the form
    $(this).closest('form').submit();
  });
});
<!-- PHP Code -->
<?php
$zac = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['button'])) {
        $buttonValue = $_POST['button'];

        if ($buttonValue === 'one') {
            $zac = 'first button has been clicked';
        } elseif ($buttonValue === 'two') {
            $zac = 'second button has been clicked';
        }
    }
}
?>

<!-- Form -->
<h1>Button Pressed: <?php echo $zac; ?></h1>
<form method="post" action="">
  <button type="submit" name="button" value="one" id="button1">Button 1</button>
  <button type="submit" name="button" value="two" id="button2">Button 2</button>
</form>

<!-- CDN jQuery 3.6.0 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


Solution

  • This should work:

    $(document).ready(function() {
    
        $('button[type="submit"]').click(function(event) {
    
            const form = $(this).closest('form');
    
            if (form.data("submitted")) {  // if already submitted
                console.log("Submit aborted (" + Math.random() + ")")   // for debugging
                return false;
            }
    
            console.log("Submit! (" + Math.random() + ")");  // for debugging
    
            form.data("submitted", true);   // store the flag into the form element
            $(this).text("Please wait...");
    
            // form.submit(); -- not needed
        });
    });
    

    The basic problem is that when you disable the button, its value cannot be sent with a 'submit'.

    Instead of disabling the button, you can set a flag and test it: if the form has already been submitted you can ignore the button click