Search code examples
phphtmljqueryforms

PHP button with jQuery and POST to return value


I have simple form to get username and want to achieve that:

  • when user click button it gets disabled to prevent multiple clicks (it may take few seconds to process all data in real scenario as calling APIs, writing to DB, etc);
  • after click new POST request needs to happen in order to capture $_POST['username'] in PHP and process the request further.

How to achieve that?

The code is like that but does not work as expected:

<?php

session_start();

// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(isset($_POST['submit-button'])) {
        $uname=$_POST['username'];
        header('Location: success.php');
    }
}

?>

<!DOCTYPE html>
<html>
  <head>
    <title>My Form</title>
  </head>
<body>

<form id="your_form_id" action="test4.php" method="post">
     <p><label>Username</label>
     <input id="username" type="text" name="username" value=""  autofocus/></p>
     <input type="submit" id="submit-button" name="submit" value="Login" />
</form>

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $("#submit-button").on("click", function(e){
        document.getElementById("submit-button").disabled = true; 
        document.getElementById("submit-button").value="Processing, please wait...";
        document.getElementById("your_form_id").submit();
    });
</script>

</body>
</html>

Solution

  • In order to achieve that the following principle can be used:

    • test-a.php (ordinary html form with jQuery and AJAX included to disable submit button and show simple 'page loader');
    • test-b.php (to process data with PHP);
    • test-c.php (to show the response).

    test-a.php:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Ajax example with Page loader</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <style>
            /*CSS for Page loader*/
            #loader {
                display: none;
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 9999;
            }
        </style>
        <script>
            $(document).ready(function() {
                $('#myForm').submit(function(e) {
                    e.preventDefault(); // stops the default action of an element from happening
                    $('#submitButton').prop('disabled', true); // disable button with id=submitButton
                    $('#loader').show(); // show "Page loader"
    
                    // send AJAX request
                    $.ajax({
                        url: 'test-b.php', //path to process PHP file
                        type: 'POST',
                        data: $(this).serialize(),
                        success: function(response) {
                            // save response to session variable
                            sessionStorage.setItem('response', response);
                            // forward to "test-c.php"
                            window.location.href = 'test-c.php';
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <form id="myForm" method="POST">
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" required><br>
    
            <label for="email">Email:</label>
            <input type="email" name="email" id="email" required><br>
    
            <input type="submit" id="submitButton" value="Submit">
        </form>
    
        <div id="loader">
            This is page loader, please wait...
        </div>
    </body>
    </html>
    

    test-b.php:

    <?php
    session_start();
    
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    // Here you can use $name and $email for further processing or to save into database
    
    // Example of printing response data
    $response = "The following data has been received:<br>";
    $response .= "Name: " . $name . "<br>";
    $response .= "Email: " . $email . "<br>";
    
    // save response to session variable
    $_SESSION['response'] = $response;
    
    // we finish work in this file
    exit;
    ?>
    

    test-c.php:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Success</title>
        <style>
            h1 {
                color: green;
            }
        </style>
    </head>
    <body>
        <h1>Process file response:</h1>
        <?php
        session_start();
    
        if (isset($_SESSION['response'])) {
            $response = $_SESSION['response'];
            echo $response;
            unset($_SESSION['response']); // unset session variable
        } else {
            echo "No data to show.";
        }
        ?>
    </body>
    </html>