radio button value in php - php

I'm trying to make a simple survey in php
I have a set of radio buttons on a page called sja.php that sends its to sjamail.php page
the problem is that when I go to get
$answer = $_POST['ans'];
I can't seen to do anything like
echo "$answer";
but if I were to throw some logic at it
like
if ($answer == "ans1") {
echo 'Correct';
}
else {
echo 'Incorrect';
}
It will display correct or incorrect (edit: The if/else works correctly and will display the correct answer )
so why is it I can't access the value of the radio button "ans" as a string?
http://www.markonsolutions.com/sja.php
print_r($_POST); will return Array ( [ans] => )

Perhaps the value is something other than text.
Try
var_dump($answer);
or
print_r($answer, TRUE);

Your page works correctly if you select any of the first 4 radio buttons (ans1/2/3/4). But the rest of the radio buttons next to all those images have blank values, which would explain why your posted value is empty if you selected any of those to test with.

You need to make sure that the field in HTML has...
<input type="radio" name="ans" value="ans1" />
<input type="radio" name="ans" value="ans2" />
Also make sure your form method is POST

I had a similar problem with the following:
<input name="03 - Gender" type="radio" value="Masculino"/>Male<br/>
<input name="03 - Gender" type="radio" value="Femenino" required="required"/>Female <br/>
<input type="hidden" name="03 - Gender" value=""/>
but when I removed the third input line (the hidden one) the problem desapeared.

Try this:
$answer = (string)$_POST["ans"];
echo $answer;
You must convert $_POST["ans"] to string.

Related

Parse radio button postback data using PHP

I have a question related to php. If anyone have an idea,please share with me. (I am a beginner in php).
I received a button value from an HTML page and displayed corresponding figure in the second page using code "param1.php". In the same program itself ( ie, "param1.php"), there is a set of radio box and i need to receive the radio value using another php program. But here i have confusion how to receive the radio value using another php program say "param2.php". also how the page redirect (to the php program where i receivvee the radio value) on selecting a radio button.
Thanks
I attach the "param1.php" below,
<!DOCTYPE html>
<html>
<body>
<br>
<?php
$data = $_POST['btn'];
$data2=$data.".png";
?>
<img src="<?php echo $data2;?>">
<h3>SCALE</h3>
<input type="radio" name="group1" value="5,10,15" checked> 5,10,15<br>
<input type="radio" name="group1" value="5,9,13"> 5,9,13<br>
</body>
</html>
No form tags
There are no form tags, so your radio tags won't get POST'd to param2.php
<form action="param2.php" method="POST">
<input type="radio" name="group1" value="5,10,15" checked> 5,10,15<br>
<input type="radio" name="group1" value="5,9,13"> 5,9,13<br>
<input type="submit" value="Process" />
</form>
Incorrect $_POST key
Now, in your param2.php file, you will be able to get the value of POST['group1']. In your code you're using the wrong key. btn doesn't exist within $_POST (in the code you've given anyway). The radio button name is group1, so access it as such;
$data = $_POST['group1'];
The value of $data will either be 4,10,15 or 5,9,13. Ensure you've got an image named 4,9,13.png and 4,10,15.png else your image won't show. Because they're comma separated, I'm going to assume these are unique file names. So;
foreach( explode(",", $_POST['group1']) as $file) {
echo "<img src='". $file .".png' />";
}
Also, ensure you do some checks on the posted data to validate the user input

why if conditon is not behaving properly in comparing values

why if conditon is not behaving properly in comparing values one which is coming from database and other coming from form via post..inside while loop of mysql fetch array
<?php
$right=0;
$wrong=0;
$result = mysql_query("SELECT * FROM mcq") ;
$total =mysql_num_rows($result);
echo "total questions are :".$total;
echo "<br>";
while($row = mysql_fetch_array($result))
{
$b=$row['id'];
$a=$_POST['a_'.$b];
$cor=$row['correct'];
if($a==$cor)
$right++;
else
$wrong++;
}
$a is coming from radio buttons from previous page and $cor is coming from database..i m comparing selected value of radio button with cor(correct answer of that value) which is coming from data base.. but condition is not executing rightly so please help me!!!!
The radio button just send one value. Your way to retrieve it is wrong, because you are basing in the ID, but the id should be used in the value.
Usually in HTML you should use some like this:
<input type="radio" name="myradio" value="item1" />
<input type="radio" name="myradio" value="item2" />
<input type="radio" name="myradio" value="item3" checked />
So, you should try to get the value from post:
$myvar = $_POST["myradio"];
Can you paste the radio button code?

Validation HTML Radio Button

I am facing a problem with simple validating of radio button though database.
What I want to do is to just simply check whether radio button for each question is selected or not. I know the simple checking. But as I am using php variable name for every radio button name, it's very hard to convert to javascript variable and check. And I am stuck at this point.
<form id="formID" method="post" action="user_anger_quiz.php?rating_finished=true">
<input type="radio" name="<?php echo $question_form_name; ?>" value="<?php echo $question_id ?>,1"/>
<input type="radio" name="<?php echo $question_form_name; ?>" value="<?php echo $question_id ?>,2" />
<p id="anger_rating_submit">
<input type="submit" value="Rate my anger level"/></p>
</form>
Any suggestions would be appreciated in advanced.
regarding to your comment:
I guess that you will use php to check it due to the fact that you just add php as a tag.
In php you can use $_POST or $_GET on action page of your form to fetch the radio buttons.
Otherwise you can use javascript / javascript library
I think you're asking to make sure there is a radio button checked before submitting? Try the below untested function using jquery to see if there is a radio button selected. Run that before the form is submitted.
function somethingChecked()
{
if (!$("input[name='<?php echo $question_form_name; ?>']:checked").val()) {
alert('You need to check something');
return false;
} else {
return true;
}
}

PHP syntax and structure for radio button and its values

Radio box code:
<input
type = "radio"
name = "choice"
value = "A" />Apples />
<input
type = "radio"
name = "choice"
value = "B" />Oranges<br />
$choice=array("A"=>1.00, "B"=>0.80);
echo $choice["A"]; // will give me the value of 1.00
echo $choice["B"]; // will give me the value of 0.80
Given the code snippet above, is there anything wrong in terms of either the HTML radio box, the array or the choices?
Nope, that looks perfectly fine.
Except for the random /> after your Apples text, but I suspect this is a typo?
You may also want to consider this. Probably what you are heading towards? :)
<?php
$choices = array("A"=>1.00, "B"=>0.80);
if(in_array($_REQUEST['choice'], array_keys($choices))) {
echo $choices[$_REQUEST['choice']];
}
else {
echo "Invalid choice received!";
}
?>
This would be the code that receives your radio choice. It makes sure the choice is valid and then prints it.
As far as i understood your question, PHP Code seems to be wrong. You have not specified an array in your html code which is done using [ ].
This is what you do in you php code to echo the selection of the radio:
echo $_REQUEST['choice'];
This will echo selected radio buttons value either A or B.
I'm not sure what are you trying to achieve, but there are several things that need your attention.
First of all, check the syntax of <input>: http://www.w3schools.com/html/html_forms.asp
So I'd change your html code to:
<form ... >
<input type="radio" name="choice" value="1.00" /> Apples
<br />
<input type="radio" name="choice" value="0.80" /> Oranges
</form>
And on server side, after actually submitting the form, just look for $_POST[ "choice" ] for your desired value (1.00 or 0.80).

Submit an HTML form with empty checkboxes

I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.

Categories