Skip to content Skip to sidebar Skip to footer

How To Capture Radio Button Value And Send It To A Php Plain Text File?

So I looked up everywhere on Stackoverflow and other forums but couldn't find a solution to my problem. Here is the problem: Create an HTML file that asks the user a question to v

Solution 1:

You can use following code to save your data into JSON file

 <form action="brianaCounted.php" method="post">
    <inputtype="radio" name="class" value="first" checked> 256
    <inputtype="radio" name="class" value="second"> 349
    <inputtype="radio" name="class" value="third"> 359
    <inputtype="submit" name="submit" value="submit">
  </form>

PHP code

<?phpif (isset($_POST['submit'])) 
{
$userChoice = array();
// read uses data from JSON file$userChoice = json_decode( file_get_contents('userChoice.json'),TRUE);
    if (isset($_POST['class']))
    {
         $value = $_POST['class'];
         $userChoice[$value]++;
    } 
    file_put_contents('userChoice.json',json_encode($userChoice));
}
?>

Solution 2:

You have to give all radio buttons, that share the same question, the same name. By doing this, it is not possible, to select multiple options anymore. To check what option has been selected, you can distinguish them by their values. Use this for HTML:

<body><p>Whats your favorite class.</p><formaction="brianaCounted.php"method="post"><inputtype="radio"name="question1"value="option1"checked> 256
    <inputtype="radio"name="question1"value="option2"> 349
    <inputtype="radio"name="question1"value="option3"> 359
    <inputtype="submit"name="submit"value="submit"></form></body>

In PHP you can check what option has been selected by checking the value of $_POST['question1']:

<?phpif (isset($_POST['submit'])) {
        $first = 0;
        $second = 0;
        $third = 0;

        // Has question1 been answered?if (isset($_POST['question1'])) {
            $answer = $_POST['question1'];

            if ($answer == "option1") {
                $first++;
            } elseif ($answer == "option2") {
                $second++;
            } elseif ($answer == "option3") {
                $third++;
            }
        }

        echo"$first, $second, $third";
    }

Post a Comment for "How To Capture Radio Button Value And Send It To A Php Plain Text File?"