How to get info from form to php of a checkbox

I got this form:

<form name="formx" id="formx" action="var.php" method="POST">
  <input type="checkbox" name="f_check1"> Check 1
  <input type="checkbox" name="f_check2">Check 2
  <input name="f_register" value="Register" type="submit">
</form>

And on the var.php file I have:

   <?php
   if($_POST['f_register'] == "Register") {
     $check1 = $_POST['f_check1'];
     $check2 = $_POST['f_check2'];
     }

 echo $check1. "<br>" ;
 echo $check2;
?> 

And when i fill the form and go to the var.php, i only get results if the checkbox is on, and i want it to say "true" if checked and "false" if not.

P.S: I'm using XAMPP to run the website.

Answers


Use this block:

 <?php
   if($_POST['f_register'] == "Register") {
     $check1 = isset($_POST['f_check1']);
     $check2 = isset($_POST['f_check2']);
     }

if($check1) echo '<br>check1 true';
else echo 'check1 false';
if($check2) echo '<br>check2 true';
else echo '<br>check2 false';
?> 

$check1 = isset($_POST['f_check1']);
$check2 = isset($_POST['f_check2']);

Unchecked checkboxes aren't sent to the server. So you can account for that with:

 $check1 = isset($_POST['f_check1']) ? true:false;
 $check2 = isset($_POST['f_check2']) ? true:false;

Try this?

<form name="formx" id="formx" action="var.php" method="POST">
<input type="checkbox" name="f_check1"> Check 1
<input type="hidden" name="f_check1" value="0" />
<input type="checkbox" name="f_check2">Check 2
<input type="hidden" name="f_check2" value="0" />
<input name="f_register" value="Register" type="submit">
</form>

Edited as requested:

The hidden field with the same name will be passed if the checkbox is not checked.


Need Your Help

Sending response from Jersey web service (HTTP-POST) to the client (Jquery AJAX)

jquery ajax json jersey

This is a Jersey web service to post data to a server and store it to the database:

How to play Video from application cache in android

android media-player android-videoview

I want to play video file from android cache folder using the following code :