user577111
user577111

Reputation: 301

Undefined Index If I Do Not Check Checkbox

I seem to have a bizarre happening here. If I check a checkbox on the form then the php script runs perfectly. If I don't check the box php reports an undefined index on another variable.

That's using IIS localhost, checking things.

On the web the published identical script works no matter what. Well, virtually identical. I have locally added a variable 'test' POST-ed to php and compared with a hard coded value. That's all.

Here's the html for the checkbox:

<tr>
<td>Publish Comment?</td>
<td><input name="publishok" value="NO" type="checkbox"> Check Box For Do spanstyle="font-weight: bold;">Not</span> Publish</td>
</tr>
<tr>

and here's the php for the variable, 'publishok' :

$IP = $_SERVER["REMOTE_ADDR"];
$publishok = $_POST['publishok'];
$test = $_POST['test'];
if ($test != 'park') die ("Wrong input. Sorry. Go back, try again"); 

I suspected my editor PSPad was adding spurious (and invisible) char codes or something so I upgraded to the latest version. No difference.

Can't think what could cause this.

Can anyone help?

Upvotes: 13

Views: 30273

Answers (5)

Ateeq Rafeeq
Ateeq Rafeeq

Reputation: 58

$_POST['wc_use_taxes'] = !isset($_POST['wc_use_taxes'])? "" : $_POST['wc_use_taxes'];

This code would set empty value in posted variable which isn't set and in case its set, that would make it equal to what posted. So i guess doing this would be good idea.

Upvotes: 0

Kwed
Kwed

Reputation: 297

<input class="form-check-input" type="hidden" id="" name="check_box" value="0"> 

<input class="form-check-input" type="checkbox" id="gridCheck" name="check_box" value="1" 
<?php if ($_POST['check_box'] == "1") {
  print "checked";
 } ?>>

Upvotes: 1

totymedli
totymedli

Reputation: 31108

This happens because the checkbox's data isn't sent to the server if it is unchecked. A little hack for this is to use a hidden input field with the same name before the checkbox, so if the checkbox is unchecked, that value will be sent instead.

<input name="publishok" value="0" type="hidden">
<input name="publishok" value="NO" type="checkbox">

Upvotes: 9

Class
Class

Reputation: 3160

I believe checkboxes and radio buttons don't send a get/post data if not selected/checked (you can verify this by doing a var_dump/print_r on $_GET/$_POST) so you should do something like:

if(isset($_POST['publishok'])){
    $publishok = $_POST['publishok'];
}else{
    $publishok = "";#default value
}

Upvotes: 5

xdazz
xdazz

Reputation: 160873

checkbox won't send the data to the server when you did not check it.

You have to use isset($_POST['publishok']) to check it whether it is checked in the server side.

Upvotes: 23

Related Questions