PHP form output multiple fields duplicate - php

Hello i want to create this array output from FORM post with PHP
Here my FORM, duplicate with javascript the DIV data with class .duplicated
<?php print_r($_POST); ?>
<form method='post'>
<input name='group_name'/>
<input name='group_'/>
<div class='duplicated'>
<input name='group_values[][name]'/>
<input name='group_values[][price]'/>
</div>
<div class='duplicated'>
<input name='group_values[][name]'/>
<input name='group_values[][price]'/>
</div>
</form>
This form return this array

It's because a empty bracket like that makes php / html create a new "key/value", make your
<input name='group_values[][name]'/>
<input name='group_values[][price]'/>
Into:
<input name='group_values[1][name]'/>
<input name='group_values[1][price]'/>
And you should see a difference, if you need it to happen by itself you can use a varaible, set it to 0 or what ever value you want your array to start from, and give it +1 each time you want a new "group" Like so:
<?php $i = 0; //Initializes the variable ?>
<input name='group_values[<?php echo $i; ?>][name]'/> //Array key = 0
<input name='group_values[<?php echo $i; ?>][price]'/> //Array key = 0
<?php $i++; //Increases the variable with 1 ?>
<input name='group_values[<?php echo $i; ?>][name]'/> //Array key = 1
<input name='group_values[<?php echo $i; ?>][price]'/> //Array key = 1
Of course it can be done in a more efficient / smarter way, but this is just to give you a basic example
For Javascript it will depend on how you duplicate the data, but the idea is basically the same
var key = 0;
var duplicateInput1 = "<input name='group_values[" + key + "][name]'/>" +
"<input name='group_values[" + key + "][price]'/>";
key++;
var duplicateInput2 = "<input name='group_values[" + key + "][name]'/>" +
"<input name='group_values[" + key + "][price]'/>";
var duplicateForm = duplicateInput1.concat(duplicateInput2);

Related

Updating multiple input values using one submit button in a loop

I have an array stored inside a session. I have echoed out each key and value using a foreach loop. Next to each key there is an input box for updating the value for that specific key.
The problem is that, each input box has its own submit button for updating the value. I want to make it only one submit that updates all input boxes.
I tried placing the submit button and the outside of the loop. But that only updates the last value in the loop and not any other one.
I tried having it even outside the php and rewriting it as html, but it still didnt work for some reason.
THANKS in advance!
MY CODE!
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
$aaa = $_POST['aaa'];
$key_var = $_POST['ke'];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<form method="post" action="">
<input type="text" name="aaa" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke" value="<?php echo $key; ?>">
<input type="submit" value="Update value of key" name="submit"/></div>
</form>
<?php
}
?>
UPDATE
So I used Vijaya Sankar N's code and Audite Marlow' code and they both work perfectly.
Updated code by Audite Marlow
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
for ($i = 0; $i < count($_POST['aaa']); $i++) {
$aaa = $_POST['aaa'][$i];
$key_var = $_POST['ke'][$i];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
}
?>
<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<input type="text" name="aaa[]" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke[]" value="<?php echo $key; ?>">
<?php
}
?>
<input type="submit" value="Update value of key" name="submit"/>
</form>
Put the form around your foreach loop. Put the submit button outside of your foreach loop, inside your form. Inside the foreach loop, make the names of your inputs an array, like so:
<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<input type="text" name="aaa[]" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke[]" value="<?php echo $key; ?>">
<?php
}
?>
<input type="submit" value="Update value of key" name="submit"/></div>
</form>
Now, in your isset($_POST['submit']) { ... }, you want to loop through your input arrays like so:
if (isset($_POST["submit"]))
{
for ($i = 0; $i < count($_POST['aaa']); $i++) {
$aaa = $_POST['aaa'][$i];
$key_var = $_POST['ke'][$i];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
}
This way, you'll update all $_SESSION['animals'] keys for every input.
The problem isn't the position of the buttons, but the form and /form tags
When you click a button that is insiede a form /form block, the browser send all the data INSIDE the block.
If you want to update ALL the elements with one button, you have to open the form tag before the "foreach" block and close the /form tag outside the foreach block
Just put everything in one form with one submit button. Than you need to make the input name unique, cause else only the last value will be submitted. I did this by creating an 'animal' input array. In your PHP you can just simply loop through the POST data.
Try this:
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
//Your new PHP to update all values
if(isset($_POST['animal']) && count($_POST['animal']) > 0)
{
foreach($_POST['animal'] as $key => $value)
{
$_SESSION['animals'][$key] = $value;
}
}
}
?>
<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<input type="text" name="animal[<?= $key ?>]" value="<?= $value ?>" size="2" />
<?php
}
?>
<input type="submit" value="Update all values" name="submit"/></div>
</form>
Move the form and button outside the foreach and generate text fields with the key as identifier.
<form method="post" action="">
<?php
foreach($_SESSION['animals'] as $key=>$value)
{
echo 'The value of key ' .$key. ' is '."'".$value."'";
echo "update the value of key " .$key. " in the input box bellow <br />";
echo "<input type='text' name='$key' value='$value' size='2' /> <br />";
}
?>
<input type="submit" value="Update value of key" name="submit"/></div>
</form>
and your PHP submit code will be as simple as:
foreach($_POST as $key=>$value){
$_SESSION['animals'][$key] = $value;
}

Not able to get $_POST assigned to a variable PHP

I assume I have something stupid happening due to my lack of experience.
On a form on members.php I have:
$column = 0;
echo "<Form Name =member Method =POST ACTION = individual.php>";
echo "<table>";
echo "<tbody>";
while($row = $rs->fetch_assoc()) {
if ($column == 0) {
echo "<tr>";
}
echo '<td><INPUT TYPE = Submit NAME="'. $row['num'].'" VALUE ="'. $row['name'].'" id=Submit></td>';
$column++;
if ($column >= 5) {
echo "</tr>";
$row++;
$column=0;
}
}
echo "</tbody>";
echo "</table>";
echo "</form>";
On individual.php I have
print_r($_POST);
With the result being Array ( [16] => LUKE ) which is what is expected.
but when I try to
$name=$_POST['name'];
$num=$_POST['num'];
echo "<br>".$name." ".$num."<br>";
I do not get any results.
I mainly want to get $row['num'] but also did ['name'] to make sure I didn't transpose what I was trying to achieve.
I basically want to take what was selected on previous form and insert into a
select * from table where number=$num;
The name of your input fields are not num and name, instead, they are the values of these two keys in the array $row. That is why you are unable to retrieve these values on the backend.
Change your code to:
<input type="hidden" name="name" value="<?php echo $row['name']; ?>;">
<input type="hidden" name="num" value="<?php echo $row['num']; ?>;">
<input type="submit" value="Submit!" name="submit_form">
For obtain POST value for 'name' and 'num', you have to write:
<input type="text" name="name" value="<?php echo $row['name']; ?>">
<input type="text" name="num" value="<?php echo $row['num']; ?>">
type can be 'text' or 'hidden'
Enjoy your code!
If you want your form to return values that you can access using $_POST['name'] and $_POST['num'], you need to set name and num as input names on your form, and the appropriate values as the input values. If you don't want to add them as visible/editable values in your form, the usual way to do it is to use inputs of type hidden:
<form action="individual.php">
<input type="hidden" name="num" value="16" />
<input type="hidden" name="name" value="LUKE" />
<input type="submit" />
</form>
As it is, $_POST does contain the values that you're want, but they're not in an accessible format, because you've set 16 as an input name, so it turns into a key in the $_POST associative array. The form above will set num and name as keys in $_POST, and 16 and LUKE respectively as the values.

Passing form information in a for-loop

Maybe this is a stupid question, but I was wondering if I could get information passed with a form into a for-loop.
The problem is as follows:
The passing of the information works, though he passes only for the last loop. For example if I click the submit button for loop 2 ($i = 2). The command $_POST['titel'] will only remember the information in last loop ($i = $numact-1) and not loop 2 ($i = 2).
for example if titel[0] = test0, titel[1] = test1, titel[2] = test2. and I click the submit button below titel[0] he passes the information from titel[2]. Is there an easy way to get around this?
I have the following code (For the sake of simplicity I shortened it);
<?php
for ($i = 0; $i <= $numact-1; $i++) {
echo "<tr><td width='150'>
<input type='text' name='titel' value='$titel[$i]' />
</td></tr>
<tr><td><input type='submit' name='submitreg' value='Toon activiteit'/>
</td></tr>";
}
?>
You're using the same parameter name over and over again (name=titel - you had a type and probably meant to write as 'title') so when the form submits - only one value will be passed.
You can easily fix that by passing the parameters as:
...
echo "<tr><td width='150'>
<input type='text' name='titel$i' value='$titel[$i]' />
</td></tr>
<tr><td><input type='submit' name='submitreg' value='Toon activiteit'/>
</td></tr>";
...
and reading it on the other side as title0, title1 etc.
As seen in this post, you can pass in an array simply by putting brackets around the index. PHP will reconstruct the array for you.
Also, you probably want your submit at the end of your table, not after each row. Your code should look something like this:
<?php
for ($i = 0; $i <= $numact-1; $i++) {
echo "<tr><td width='150'>
<input type='text' name='titel['.$i.']' value='$titel[$i]' />
</td></tr><tr><td><input type='submit' name='submitreg' value='Toon activiteit'/>
</td></tr>";
}
?>
The advantage of this approach is that it's more extensible, should you choose to use different values. However, Edson Junior's approach is slightly simpler.
You can change the name attribute to name=titel[] so PHP will automatically transform it to an array. It is not necessary to specify the index inside title[].
For example:
<input type="text" name="titel[]" value="x" />
<input type="text" name="titel[]" value="y" />
<input type="text" name="titel[]" value="z" />
When you submit the form, PHP will transform it to
"title" = array (
0 => "x",
1 => "y",
2 => "z"
);
In case you need to check what button was clicked, you could change the inputs type="submit" to <input type="button" name="submitreg" class="submitreg" id="whatever_you_want_but_has_to_be_unique" />.
Outside the loop, add another input wich will have the value of what button was pressed.
<input type="hidden" id="buttonPressed" name="buttonPressed" value="" />
Then add this code (you need to import jQuery library to the page so it understands the code below, wich is jQuery, here is the Docs.
<script type="text/javascript">
$(function(){
$("button.submitreg").live("click", function(){
var buttonPressed = $(this).attr("id");
("input#buttonPressed").val(buttonPressed);
});
}
</script>
All you need to do is get the buttonPressed value and you'll know what button was pressed.

How can i output Ajax Value to a PHP Variable?

Problem :
There is a Value1 that is calculated from Ajax Function addToAuthorizeform();
There is a Value2 that is a PHP varibale $amount. This variable should show the output of the value1 that is calculated by Ajax Function.
How it is possible?
My code so far:
//AJAX FUNCTION THAT OUTPUTS AN AMOUNT
//SEE LINE 24 value="'+arrData[1]+'" <-- This is the correct value that needs to be //output on PHP VARIABLE
<script>
function addToAuthorizeForm() {
$wbc('#slots_purchased').html('');
var new_html = '';
var i = 1;
$wbc('#booking_slots').find('input').each(function () {
if ($wbc(this).attr('checked')) {
var slot_id = $wbc(this).val();
//ajax request to get data
$wbc.ajax({
url: '<?php echo plugins_url('
my_plugin / public ');?>/ajax/getSlotInfo.php?slot_id=' + $wbc(this).val(),
success: function (data) {
arrData = data.split("$");
if (arrData[1] > 0) {
q = 1;
if ($wbc('#seats_' + slot_id).val() != undefined) {
q = $wbc('#seats_' + slot_id).val();
}
new_html += '<input type="hidden" name="x_amount_' + i + '" value="' + arrData[1] + '" />';
$wbc('#slots_purchased').html(new_html);
i++;
}
}
});
}
});
}
</script>
Now The PHP Variable is
$amount = '';
Now I need to know what code should I put after $amount = 1 so I can call or echo the Ajax same value '+arrData[1]+' that is calculated on line 24 of the Javascript Function.
Here is the Authorize.net HTML form that i am using to Submit.
<?php
require_once 'anet_php_sdk/AuthorizeNet.php'; // Include the SDK you downloaded in Step 2
$fname = $bookingReservationObj->getReservationName();
$api_login_id = $bookingSettingObj->getAuthorizeAPI();
$transaction_key = $bookingSettingObj->getAuthorizeTXN();
$amount = // I am not sure what to put here to call Ajax value that i need answer
$fp_timestamp = time();
$fp_sequence = "123" . time(); // Enter an invoice or other unique number.
$fingerprint = AuthorizeNetSIM_Form::getFingerprint($api_login_id,
$transaction_key, $amount, $fp_sequence, $fp_timestamp)
?>
<!-- authorize.net form -->
<form action='https://test.authorize.net/gateway/transact.dll' METHOD='POST' name="authorize_form" style="display:inline">
<!-- Authorize Configuration -->
<input type='hidden' name="x_login" value="<?php echo $api_login_id ?>" />
<input type='hidden' name="x_fp_hash" value="<?php echo $fingerprint?>" />
<input type='hidden' name="x_fp_timestamp" value="<?php echo $fp_timestamp?>" />
<input type='hidden' name="x_fp_sequence" value="<?php echo $fp_sequence?>" />
<input type='hidden' name="x_version" value="3.1">
<input type='hidden' name="x_show_form" value="payment_form">
<input type='hidden' name="x_test_request" value="true" />
<input type='hidden' name="x_method" value="cc">
<input type='hidden' name="x_first_name" value="<?php echo $fname ?>">
<input type='hidden' name="x_last_name" value="<?php echo $fname ?>">
<input type='hidden' name="x_email" value="<?php echo $fname ?>">
<input type='hidden' name="x_phone" value="<?php echo $fname ?>">
<input type='hidden' name="x_description" value="<?php echo 'Cruzz Booking '; ?>">
<!--slots purchased-->
<div id="slots_purchased">
</div>
<input type='hidden' name="x_receipt_link_method" value="link">
<input type='hidden' name="x_receipt_link_text" value="Click here to return to our home page">
<input type='hidden' name="x_receipt_link_URL" value="<?php echo site_url('')."/?p=".$post->ID."&authorize_confirm=1"; ?>">
<input type="hidden" name=" x_cancel_url" value="<?php echo site_url('')."/?p=".$post->ID; ?>">
<input type="hidden" name="rm" value="POST">
</form>
How should I start?
In your code $wbc must be your jQuery Object, it's normally just $. If for some reason $wbc does not refer to the jQuery Object you have a problem. ajax is a method of the jQuery Object. The ajax method takes an Object Literal as its argument. A JavaScript Object Literal is really an Associative Array. url is a property of the Object You are passing in as an argument. The value for that property is '<?php echo plugins_url('my_plugin/public');?>/ajax/getSlotInfo.php?slot_id='+ $wbc(this).val(), which you must be running through your server, so this must be a .php file. To use plugins_url() you must be using WordPress.
You are using the $wbc.ajax({type:'GET'}) method so additional information can be sent like 'getSlotInfo.php?slot_id='+$wbc(this).val()+'&anotherProperty=anotherValue. So the & seperates properties.
See where your code says getSlotInfo.php?slot_id=? The slot_id part can be accessed with $_GET['slot_id'] on the page your url is sending information to, which happens to be getSlotInfo.php. You can use <?php $varHere = $_GET['slot_id'] ?> on your getSlotInfo.php page to create a PHP variable that holds jQuery.
If you had a dataType: 'json' in your ajax method Object argument, like $wbc.ajax({dataType: 'json'}), then you could use PHP to generate JavaScript Object Notation, which is an Associative Array. The PHP method of choice for this on your getSlotInfo.php page will be json_encode(). As long as you print or echo json_encode() with PHP, when you have a successful response the data argument of $wbc.ajax({success: function(data){}}) will hold the Associative Array, which can be used with JavaScript's for in loop like:
for(var i in data){
var property = i;
var value = data[i];
}
Your PHP, on getSlotInfo.php, that sends to this JavaScript Object Literal might look like:
<?php
if(isset($_GET['slot_id']) && isset($_GET['anotherProperty'])){
$ary = array('prop1' => $_GET['slot_id'], 'prop2' => $_GET['anotherProperty']);
echo json_encode($ary);
}
else{
header('LOCATION: urlOfChoice.html');
}
?>
Using this methodology there is no reason to split the data since its not a string response. Instead it's already JSON.
This might help you understand the post method Jquery AJAX post to PHP.

submit multiple forms with single submit button in javascript

i have 1 php page containing 2 forms and 1 submit button.i want to submit both forms with this single button.My code works perfectly but there is 1 problem that in each form only 1 field submitted successfully. Below is my html and javascript code, plz tell me where i have error
2 html forms
<form name="form">
<input type="text" name="a" value="a">
<input type="text" name="b" value="b">
</form>
<form name="form">
<input type="text" name="c" value="c">
<input type="text" name="d" value="d">
</form>
<input type="submit" name="Submit" id="button" value="Submit" onClick="submitAllDocumentForms()">
Javascript code
<script language="javascript" type="text/javascript">
/* Collect all forms in document to one and post it */
function submitAllDocumentForms() {
var arrDocForms = document.getElementsByTagName('form');
var formCollector = document.createElement("form");
with(formCollector)
{
method = "post";
action = "test.php";
name = "formCollector";
id = "formCollector";
}
for(var ix=0;ix<arrDocForms.length;ix++) {
appendFormVals2Form(arrDocForms[ix], formCollector);
}
document.body.appendChild(formCollector);
formCollector.submit();
}
/* Function: add all elements from ``frmCollectFrom´´ and append them to ``frmCollector´´ before returning ``frmCollector´´*/
function appendFormVals2Form(frmCollectFrom, frmCollector) {
var frm = frmCollectFrom.elements;
for(var ix = 0 ; ix < frm.length ; ix++)
frmCollector.appendChild(frm[ix]);
return frmCollector;
}
</script>
My php code to echo submitted values
<?php
echo $_POST['a'];
echo $_POST['b'];
echo $_POST['c'];
echo $_POST['d'];
?>
The problem is that appendChild() takes the element away from the form, modifying the elements array as well as its length. To avoid this, you can e.g. store the number of elements in a variable and process the array of elements starting from the last element:
var frm = frmCollectFrom.elements;
var nElems = frm.length;
for(var ix = nElems - 1; ix >= 0 ; ix--)
frmCollector.appendChild(frm[ix]);

Categories