I want to assign a value to a variable in radi button. I tried a code like this

<form method="post" action="">  <input type="submit" name="task" value="CONTINUE" onclick="$lax="5">





$task = $_POST['task'];
    switch( $task ) { 
    case 'CONTINUE':
    echo $lax;

i want the variable lax to get the value 5 while entering the switch case. I'm very new to php pls help.

Dani AI

Generated

Short, practical clarification for (and to follow up on 's point): an onclick attribute runs in the browser (client-side). PHP runs on the server when the form is submitted. A client-side click cannot directly set a PHP variable unless the value is sent to the server (form field or Ajax). Two simple fixes follow.

Use a radio input so the chosen value is sent with the POST request, then read it with PHP:

<form method="post" action="">
  <label><input type="radio" name="lax" value="5"> Option 5</label>
  <label><input type="radio" name="lax" value="10"> Option 10</label>
  <input type="submit" name="task" value="CONTINUE">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $task = $_POST['task'] ?? '';
    $lax  = isset($_POST['lax']) ? intval($_POST['lax']) : null;
    switch ($task) {
        case 'CONTINUE':
            echo $lax;
            break;
    }
}
?>

If a radio is not wanted, set a hidden field from JavaScript before submit (onclick runs before the form posts):

<form method="post" action="">
  <input type="hidden" name="lax" id="lax" value="">
  <input type="submit" name="task" value="CONTINUE"
         onclick="document.getElementById('lax').value='5'">
</form>

Notes and cautions: always validate/sanitize server-side (use intval() or filter_input()), check isset() to avoid undefined indexes, and never trust client-sent values for security-sensitive logic. If a server response without a full page reload is required, send the value with Ajax instead of a normal form submit.

First, where is your radio button ? You just posted only form and submit button. You can process PHP directly with javascript onclick event except using Ajax. You must submit the form and process at server-side then assign value in server-side or print to client-side (browser). Ensure what you want to achieve and post clearly again what you need with your codes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.