简体   繁体   中英

this.form.submit() with PHP isset?

echo "<form method=\"post\" action=\"settings.php\" onchange=\"this.form.submit()\">";
echo "Announce New Files: <input type=\"radio\" name=\"announcefiles\" value=\"On\" $checkon1> On";
echo "<input type=\"radio\" name=\"announcefiles\" value=\"Off\" $checkoff1> Off<br>";
echo "</form>";

I am trying to get this form to submit when one of the radio buttons is pressed but I'm not sure how to catch the submission.

for example, normally with a submit button you would use something along the lines of if(isset($_POST['submit'])) but I'm not sure how to do it if the form auto submits.

Add hidden input field like:

<input type="hidden" name="action" value="submit" />

Then in PHP check:

if(isset($_POST["action"]) && $_POST["action"] == "submit") { ... }

Give your form a name and check for isset($_POST['form_name']) or check for the name of the radio isset($_POST['announcefiles'])

Also, you don't need all the quote escaping that you have, you can use single quotes as well as use a multiline string - see example below.

echo "
<form method='post' name='form_name' action='settings.php' onchange='this.form.submit()'>
Announce New Files: <input type='radio' name='announcefiles' value='On' $checkon1> On
<input type='radio' name='announcefiles' value='Off' $checkoff1> Off<br>
</form>";

<?php
    // Check if form was submitted
    if (isset($_POST['form_name']) {
        // Form submitted
    }
?>

<?php
    // Check if radio was selected
    if (isset($_POST['announcefiles']) {
        // Form submitted
        echo 'You chose' . $_POST['announcefiles'];
    }
?>

You should be checking the request method. If you've set things up cleanly, a POST request at that URL will mean a form submit. As you've noticed, you can have attempted submits where a value just isn't there.

if ($_SERVER['REQUEST_METHOD'] === 'POST')

See $_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST' for more discussion.

Try this:

You may have an easier time if you separate the php and html a little more.

<form method="post" action="settings.php" onchange="this.form.submit()">
    <fieldset>
        <legend>Announce New Files:</legend>
        <label for="on"><input type="radio" id="on" name="announcefiles" value="On" <?php echo $checkon1 ?> /> On</label>
        <label for="off"><input type="radio" id="off" name="announcefiles" value="Off" <?php echo $checkoff1 ?> /> Off</label>
    </fieldset>
</form>

Then in your php logic in settings.php ( or above the form if you are posting back to the same page ) you can check for the value of announcefiles :

<?php
    if(isset($_POST['announcefiles'])){
        // DO SOMETHING
    }
?>

Let me know if this helps. Or if I'm missing the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM