Search code examples
phpisset

Why PHP can't recognize when the input[type='button'] is clicked on?


I just want to simply echo 'OK!' when the input with type="button" name="calculateBtn" is clicked on, but PHP does not recognize that with the condition if (isset($_POST['calculateBtn'])) so wouldn't do anything, can somebody please tell me why is that?

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div class="container">
    <div class="row">
        <form action="" method="post">
            <div>
                <input id="input" type="text">
                <?php
                if (isset($_POST['calculateBtn'])) {
                    echo 'ok';
                }
                ?>
                <input name="calculateBtn" value="change the value" type="button">
            </div>
        </form>
    </div>
</div>
</body>
</html>


Solution

  • First, you don't have an action defined in the form, second the button type is set as a button instead of submit, it will not submit the form.

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <form action="page.php" method="post">
                <div>
                    <input id="input" type="text">
                    <?php
                    if (isset($_POST['calculateBtn'])) {
                        echo 'ok';
                    }
                    ?>
                    <input name="calculateBtn" value="change the value" type="submit">
                </div>
            </form>
        </div>
    </div>
    </body>
    </html>
    

    please set the page.php to the name of your page(file).