Skip to content
Advertisement

PHP Post radio value to next page on radio click

I need some help with my code as I have got a problem with posting the value. When I click on the radio, it will not post the data when it redirect me to secondpage.php. I want to post the value when I click on the radio button to take me to the next page.

firstpage.php

<table>
    <form name="frmProfile" method="post" action="secondpage.php">
        <tr>
            <td>gender</td>
            <td><input type="radio" name="gender" onclick="document.location.href='http://example.com/secondpage.php'" data-gender="female" value="female">Female
                <input type="radio" name="gender" onclick="document.location.href='http://example.com/secondpage.php'" data-gender="male" value="male">Male</td>
        </tr>
        <tr><td colspan="2"><input type="submit" name="submit" value="Submit" /></td></tr>
    </form>     
</table>

secondpage.php

print_r($_POST);

?>

It will show the empty data in the $_POST as I will get the results which it show Array ( ) when I am using print_r($_POST) in secondpage.php.

What I am trying to achieve is when I click on a radio button, I want to post the data to redirect me to secondpage.php and display the data of Male or Female depends on the radio button that I click on.

Can you please show me an example how I could post the value of the radio that I select on to redirect me to the secondpage.php to display the data of $_POST?

Thank you.

Advertisement

Answer

You can bind a click event listener to the form. When a click happens, check if it originated from one of the radio elements. If it did, submit the form.

document.getElementById('genderForm').addEventListener('click', function(e){
                                  // 'this' is the genderForm
  if (e.target.name === 'gender') this.submit();
});
<form id="genderForm" name="frmProfile" method="post" action="secondpage.php">
  <table>
    <tr>
      <td>gender</td>
      <td>
        <input type="radio" name="gender" value="female">Female
        <input type="radio" name="gender" value="male">Male
      </td>
    </tr>
  </table>
</form>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement