alter $_POST data of radio select option - php

So I have a Radio button group, like so:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose a pet:</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
<input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
</fieldset>
</div>
Now if I just submit the for I get this $_POST (Note I have multiple Radio group questions)
Array
(
[radio-choice-1] => choice-1
[radio-choice-2] => choice-4
[radio-choice-3] => choice-2
[submit] => submit
[PHPSESSID] => 11111111111111111
)
How Can I restructure the HTML or $_POST data before submission to make it look like this:
Array
(
[type-1] => radio-choice-1
[answer-1] => choice-1
[type-2] => radio-choice-2
[answer-2] => choice-4
[type-3] => radio-choice-3
[answer-3] => choice-2
[submit] => submit
[PHPSESSID] => 11111111111111111
)
Maybe jQuery as an option?

You can do it post submission, the code below should work if you keep your original naming conventions.
$postValues = $_POST;
$altered = Array();
$unaltered = Array();
foreach ($postValues as $key => $val) {
if ( FALSE !== stripos($key, 'radio-choice-') ) {
$num = explode('-', $key);
$num = $num[2];
$altered['type-'.$num] = $key;
$altered['answer-'.$num] = $value;
} else {
$unAltered[$key] = $value;
}
}
$manipulatedPOSTData = array_merge($altered, $unAltered);
// Keep doing what you intended

I assume you are talking about a form that you are submitting?
If you want to add finer control over what gets posted, you can do one of two things:
1) add hidden variables
or
2) use jQuery .post() (http://api.jquery.com/jQuery.post/) instead of doing a normal form submission.
Personally, I think the first of the two is simplest:
<div data-role="fieldcontain">
<input type="hidden" name="type-1" value="radio-choice-1" />
<fieldset data-role="controlgroup">
<legend>Choose a pet:</legend>
<input type="radio" name="answer-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="answer-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
<input type="radio" name="answer-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="answer-1" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
</fieldset>
</div>
By changing the name of the radio ground to answer-1 and adding a hidden variable, that should meet your requirements (do the same for your other radio elements).

Avoid client side elaboration if you can.
Otherwise use .submit() and hand code what you need. but it's harder.

Related

PHP For loop for $_POST

Sorry for the noob question. But I am stuck here.
This is my HTML form where the user-form div can be cloned to as many as possible. The #submit-form div has some hidden values which are common for all.
HTML -
<div class="user-form">
<input type="text" autocomplete="off" name="name[]" >
<input type="email" autocomplete="off" name="mail[]" >
</div>
<div class="user-form">
<input type="text" autocomplete="off" name="name[]" >
<input type="email" autocomplete="off" name="mail[]" >
</div>
<div id="submit-form">
<input type='hidden' name='refer_user_id' value='<?php echo $refer_user_id ?>'>
<input type='hidden' name='refer_user_email' value='<?php echo $refer_user_email ?>'>
<input type="submit" value="Invite" />
<input type="button" class="button" id="clonetrigger" value="Clone" />
</div>
I'm using ajax to submit the form. Basically I want to create accounts using the name and email fields. In PHP How do I use foreach to loop through the name and email fields so that I can create unique accounts?
My print_r($_POST); array looks like this.
Array
(
[name] => Array
(
[0] => david
[1] => Mark
[2] => cindy
)
[mail] => Array
(
[0] => david#abc.com
[1] => mark#abc.com
[2] => cindy#abc.com
)
[refer_user_id] => 2
[$refer_user_email] => test#abc.com
)
Create a loop with a number of iterations equal to the number of submitted name/email pairs, then use the loop counter to access the values for each user.
for ($i = 0; $i < count($_POST['name']); $i++) {
{
$name = $_POST['name'][$i];
$mail = $_POST['mail'][$i];
// Process the new user
}
go through one of the arrays with a foreach, use the key for the second array.
foreach($_POST['name'] as $key =>$name ){
$mail = $_POST[$key];
}
foreach($_POST['name'] as $key => $val) {
echo $val
}
foreach($_POST['mail'] as $key => $val) {
echo $val
}
Easiest way to loop through those elements. You can reference the other elements with $_POST['refer_user_id']. While this works for the purposes of a foreach, the for loop posted above is more efficient, so I'd recommend using it.
http://php.net/manual/en/control-structures.foreach.php More reading on it here.
You can use array_combine function:
$data = array_combine($_POST['name'],$_POST['mail']);
foreach($data as $name=>$mail){
print $name;
//...
}
See array_combine.
You could also use the JavaScript that's auto-generating the form items to give them a name that would result in linking the php object. i.e.
<div class="user-form">
<input type="text" autocomplete="off" name="user[1][name]" />
<input type="email" autocomplete="off" name="user[1][mail]" />
</div>
<div class="user-form">
<input type="text" autocomplete="off" name="user[2][name]" />
<input type="email" autocomplete="off" name="user[2][mail]" />
</div>
Then you could loop through the pairs with foreach($_POST['user'] as $key=>$value) etc...

Get each chekbox group values into separate variables upon form submission

I have multiple checkbox groups, and once the form is submitted, I want each group of checkboxes that were selected to be added to their own variable.
This is the form:
<form action="" method="get">
<p>apple <input type="checkbox" value="apple" name="fruits[]" /></p>
<p>orange <input type="checkbox" value="orange" name="fruits[]" /></p>
<p>peach <input type="checkbox" value="peach" name="fruits[]" /></p>
<br>
<p>red <input type="checkbox" value="red" name="colors[]" /></p>
<p>green <input type="checkbox" value="green" name="colors[]" /></p>
<p>blue <input type="checkbox" value="blue" name="colors[]" /></p>
<br>
<p>chicken <input type="checkbox" value="chicken" name="meats[]" /></p>
<p>pork <input type="checkbox" value="pork" name="meats[]" /></p>
<p>lamb <input type="checkbox" value="lamb" name="meats[]" /></p>
<button>submit</button>
</form>
And this is my code:
$string = 'fruits,colors,meats';
$str_array = explode(',', $string);
foreach ($str_array as $value) {
if (isset($_GET[$value])) {
$group_name = $_GET[$value];
foreach ($group_name as $group_item) {
$group_string .= ' ' . $group_item;
}
}
}
echo $group_string;
With that code, if I choose for example the first checkbox in each group and hit submit, I will get the following value of $group_string = apple red chicken in one string.
What I get does make sense to me as per the code I wrote, but what I want is for each option group to have its own variable to which its values are asigned, so what I want is to get is the following (assuming I again chose the first option from each group):
$fruits = 'apple';
$colors = 'red';
$meats = 'chicken';
But I don't know how to rewrite it so I get that. Also, the number of options groups is not known upfront, it has to happen dynamically.
Ok, I took the liberty of rewriting part of your php for my convenience but here it is
your new and improved php file
<?php
// assume we know beforehand what we are looking for
$groups = explode(',','fruits,colors,meats');
foreach ($groups as $group) {
if (isset($_GET[$group])) {
$vv = array();
foreach ($_GET[$group] as $item) $vv[] = $item;
$$group = implode(' ',$vv);
}
}
var_dump($fruits,$colors,$meats);
?>
I used a construct in PHP called variable variables. This is actually an almost identical answer as the one #Lohardt gave. I hope this can help you out. If it doesn't then post me a comment
You could do something like:
<input type="checkbox" value="apple" name="groups[fruits][]" />
<input type="checkbox" value="apple" name="groups[colors][]" />
<input type="checkbox" value="apple" name="groups[meats][]" />
Your $_POST will look like this:
Array
(
[groups] => Array
(
[fruits] => Array
(
[0] => apple
)
[colors] => Array
(
[0] => red
)
)
)
And it should be simple to use a foreach loop to get the keys and values.
Edit: then you can assign the value to variables like this:
${$key} = $value;
and use it you would do any variable:
echo $color;

Post values of a checkbox

I have this code on my form for the checkboxs:
<input type="hidden" name="option_desc[]" value="option 1"/>
<label><input type="checkbox" name="option_price[]" value="10" class="option_checkbox"/>option 1</label>
<input type="hidden" name="option_desc[]" value="option 2"/>
<label><input type="checkbox" name="option_price[]" value="20" class="option_checkbox"/>option 2</label>
<input type="hidden" name="option_desc[]" value="option 3"/>
<label><input type="checkbox" name="option_price[]" value="30" class="option_checkbox"/>option 3</label>
I'm trying to get the POST values of the checkbox that the user checked (for example, if he checked the second checkbox: "option 2" + "20") and store them:
$articleDetails['options'] = array();
$count = 0;
if(is_array($_POST['option_price'])){
foreach($_POST['option_price'] as $key => $value){
if($value){
$articleDetails['options'][$count]['option_price'] = $_POST['option_price'][$key];
$articleDetails['options'][$count]['option_desc'] = $_POST['option_desc'][$key];
$count++;
}
}
}
When the user check one of the checkbox, the appropriate 'option_price' is stored correctly, but the 'option_desc' is not the one that belongs to the CHECKED checkbox (for example: when the second checkbox is checked the values that I get are "20" (GOOD) and "option 1" (NOT GOOD).
What I'm doing wrong?
Thanks.
The problem you are having is that if checkboxes are not checked, the data won't get POSTed while your hidden inputs will always be posted. Frankly, I don't see what value your hidden inputs give you here. They tell you absolutely nothing about the posted data that you don't already know about on the server.
You should simply use a defined index in your array notation for the checkbox field, like this:
<input type="checkbox" name="option_price[1]" value="10" class="option_checkbox"/>option 1</label>
<input type="checkbox" name="option_price[2]" value="20" class="option_checkbox"/>option 2</label>
<input type="checkbox" name="option_price[3]" value="30" class="option_checkbox"/>option 3</label>
Note: I didn't use zero-indexed array here as I figured you might want to directly relate $_POST['option_price'][1] to "option 1".
To add some examples related to the discussion in comments below. Say for example you had some option_price checkboxes you want to output, and they come from some dynamic source. Your code to to generate the checkboxes might look something like this:
$price_options = array(
array(
'description' => 'eBook',
'value' => 10
),
array(
'description' => 'articles',
'value' => 20
),
// and so on
);
$count = count($price_options)
for($i = 1; $i<= $count; $i++) {
?>
<input type="checkbox" name="option_price[<?php echo $i; ?>]" value="<?php echo $price_options[$i]['value']; ?>" class="option_checkbox"/><?php echo $price_options[$i]['description']; ?></label>
<?php
} // end for
When POSTing you know that every $_POST['option_price'][x] would correspond to the item at $price_options[x].
You could simply iterate of $_POST['option_price'] to see which items are selected like this:
if(!empty($_POST['option_price']) {
foreach ($_POST['option_price'] as $index => $value) {
// verify value hasn't been tampered with
if ((int) $value === $price_options[$index]['value']) {
// set description
$description = $price_options[$index]['description'];
var_dump($description, $value);
}
}
}
I would suggest give names to input like
<input type=hidden name="option[1][desc]"/>
<input type=hidden name="option[1][price]"/>
Then I think it would be easy to run a forreach as well.

PHP implode function not working right

So I am trying to email the results of a form using PHP. inside my form I have a bunch of checkboxes. The script below works when at least 1 checkbox in a group is checked. If none of the checkboxes are checked I receive the following error:
Warning: Implode() [function.implode]: Invalid augments passed in {name of php doc} on line {xxx} Array
Here is a sample of the code I'm using:
<?php
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
if(!$data[14]) //$data[14] is an array of checkbox values
{echo 'No User Selection';}
else
{echo implode(" | ", $data[14]);} //This is where the error occurs
?>
HTML code
<label for="b0" class="left">Item 1</label>
<input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
<label for="b1" class="left">Item 2</label>
<input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
<label for="b2" class="left">Item 3</label>
<input type="checkbox" name="b[2]" id="b2" value="Item 3"/>
ect....
Does anyone have an idea why I'm receiving this error?
Make sure the variable a) is set and b) is an array.
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
if ( !isset($data[14]) || !is_array($data[14]) ) {
echo 'No User Selection';
} else {
echo implode(" | ", $data[14]);
}
Always properly check variables using isset(), unless of course you like giant error logs! I also suggest using the $_POST keys as the keys for $data, thus making life even easier when you want to look up a specific $_POST item.
If the checkbox is not checked, it is not sent to the server.
I suggest you to do something like this:
<label for="b0" class="left">Item 1</label>
<input type="hidden" name="b[0]" value=""/>
<input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
<label for="b1" class="left">Item 2</label>
<input type="hidden" name="b[1]" value=""/>
<input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
<label for="b2" class="left">Item 3</label>
<input type="hidden" name="b[2]" value=""/>
<input type="checkbox" name="b[2]" id="b2" value="Item 3"/>
This way, you are sure that b[0], b[1], etc. are always sent
You are causing the problem yourself by making the data array. Just go straight to the POST array. Everything else is overcomplicating the problem.
<?php
if(!isset ($_POST['b']) || !is_array($_POST['b'])) {
echo 'No User Selection';
} else {
echo implode(" | ", $_POST['b']);
}
?>
In addition, if the content of your form changes slightly, or you want to reorder the fields then your magic number 14 will no longer work.
Your code will be unbelievably fragile unless you change it.

Combine arrays depending on checked boxes

I have a form with check boxes.
I want it so that when a check box is checked, it includes an array.
<input type="checkbox" name="main" value="main" checked> Main/unsorted<br />
<input type="checkbox" name="art" value="art" checked> Art/literature/music<br />
<input type="checkbox" name="games" value="games" checked> Games/gaming<br />
If main is checked include the array 'main', if art is checked include the array 'art', etc.
I've tried, but I can't find a function that would work for this scenario.
Edit: I'm cheating a bit and am now doing it like so.
foreach($_GET as $get) {
$end = array_merge($end, $$get);
}
From your information it sounds like you want to merge an array depending on which checkboxes have been ticked? Am I correct in assuming this?
Is something like this what you are looking for?
<?php
$combinationArray = array();
$mainArray = array('item1','item2','item3');
$artArray = array('item4','item5','item6');
$gamesArray = array('item7','item8','item9');
if(isset($_POST['main']) && $_POST['main']=='main'){
$combinationArray = array_merge($combinationArray,$mainArray);
}
if(isset($_POST['art']) && $_POST['art']=='art'){
$combinationArray = array_merge($combinationArray,$artArray);
}
if(isset($_POST['games']) && $_POST['games']=='games'){
$combinationArray = array_merge($combinationArray,$gamesArray);
}
?>
HTML:
<form action="yourpage.php" method="post">
<input type="checkbox" name="main" value="main" checked> Main/unsorted<br />
<input type="checkbox" name="art" value="art" checked> Art/literature/music<br />
<input type="checkbox" name="games" value="games" checked> Games/gaming<br />
<button>
Submit
</button>
</form>

Categories