Extra added field value to be sent in post method - php

After adding the extra field using javascript, the extra field values are not being sent by post method in php. Here in the code adding the basic 5 fields, rest are the extra fields that user can add if necessary
The code is as follows:
<script language="javascript">
var i = 11;
function changeIt()
{
my_div.innerHTML = my_div.innerHTML +"<tr><td> <input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/></td><td><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/></td><br/></tr>";
i++;
}
</script>
<body>
Please enther the grocery items
<table>
<tr>
<th> Item name</th><th> kg/No of packet</th>
</tr>
<form method="post" action="gl.php">
<tr> <td><input id="item1" name="item1" type="text" maxlength="255" value=""/></td><td><input id="kgorp1" name="kgorp1" type="text" maxlength="3" value=""/></td></tr>
<tr> <td><input id="item2" name="item2" type="text" maxlength="255" value=""/></td><td><input id="kgorp2" name="kgorp2" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item3" name="item3" type="text" maxlength="255" value=""/></td><td><input id="kgorp3" name="kgorp3" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item4" name="item4" type="text" maxlength="255" value=""/></td><td><input id="kgorp4" name="kgorp4" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item5" name="item5" type="text" maxlength="255" value=""/></td><td><input id="kgorp5" name="kgorp5" type="text" maxlength="3" value=""/></td></tr>
<tr id="my_div"></tr>
<tr> <td><input id="saveForm" type="submit" value="Submit List" /></td><td><input id="addtxt" type="button" name="addtxt" value="Add more items" onClick="changeIt()" /></td> </tr>
</form>
</table>
</body>
The php code for retrieving the data sent via post method,
$i=1;
foreach ($_POST as $param_value) {
if ( empty( $param_value ) ) {
} else {
echo "<td>$param_value</td>";
if ( ( $i % 2 ) == 0 ) {
echo "</tr> <tr>";
}//echo $i;
}
$i++;
}

The problem is with how your form tag is placed and parsed in the HTML DOM.
Put the form tag higher in the document, after the tag.
<body>
Please enther the grocery items
<form method="post" action="gl.php">
and then change the javascript to this:
function changeIt()
{
var child = document.createElement('td');
child.innerHTML = "<input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/>";
document.getElementById("my_div").appendChild(child);
i++;
}
What you should get when you do a print_r($_POST) is:
Array ( [item1] => [kgorp1] => [item2] => [kgorp2] => [item3] => [kgorp3] => [item4] => [kgorp4] => [item5] => [kgorp5] => [item6] => [kgorp6] => [item7] => [kgorp7] => [item8] => [kgorp8] => [item9] => [kgorp9] => [item10] => [kgorp10] => [item11] => [kgorp11] => )
A better solution is to get rid of the table and tr/td tags and work with divs/spans for the form (its a lot nicer way to code, honestly :) )

Instead of using it in a function, simply put it inline inside your form in the following manner,
document.write('<input type="hidden" name="whatever" value="'+i+'">');
and make the adjustments necessary according to what you need.

for(i=0;i<=11;i++) {
document.getElementById("my_div").innerHTML = document.getElementById("my_div").innerHTML +"<tr>
<td> <input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/></td>
<td><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/></td>
<br/>
</tr>";
}
Demo

I don't see where the my_div variable is initialized.
You could do, in the beginning of your changeIt function:
var my_div = document.getElementById('my_div')
Then another problem: don't name this variable my_div while it's actually a tr tag.
And further: in this tr tag, your changeIt function will include HTML containing another tr, so you'll end up with bad HTML. A suggestion: do not use tables but instead, div or li tags for such a listing.

Related

PHP Form Fields with Int as name for json array

I have the following code which works well to get specific values and strip the strings like I need. However, I want to grab the fields with an int for the name and place those into an json array under my custom fields section. How can I iterate over the fields and find all fields with an int for the name then use that as the json ID with the passed value as the json value? IE:
input type="text" name="24349163" value="Here"
JSON encoded:
"id"=>'24349163', "value" =>'value of the field I need'
What I have now:
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array('subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']), 'requester' =>
array('name' => $arr['z_name'], 'email' => $arr['z_requester']),
'custom_fields' => array("id"=>'24349163', "value" =>'Here'))));
Form for post:
<form id="zFormer" method="post" action="tickets.php" name="zFormer">
<table>
<tr>
<td valign="top">
<label for="z_name">Your Name:</label>
<input type="text" value="John Doe" name="z_name" />
</td>
<td valign="top">
<label for="z_requester">Your Email Address: </label>
<input type="text" value="john#domain.com" name="z_requester" />
</td>
</tr>
<tr>
<td valign="top">
<label for="z_subject">Title/Subject: </label>
<input type="text" value="Who needs a subject?" name="z_subject" />
</td>
<td valign="top">
<label for="z_description">Summary Description:</label>
<textarea name="z_description">Systems are down</textarea>
</td>
</tr>
<tr>
<td valign="top">
<label for="24275273">Incident Start Date:</label><br/>
<input type="date" name="24275273" value="" />
</td>
<td valign="top">
<label for="24275293">Incident Start Time:</label><br/>
<input type="time" name="24275293" value="" />
</td>
</tr>
I am not 100% sure I understand the question, but it sounds like you need to add an else in your foreach:
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
elseif(is_numeric($key)) {
$arr['ticket']['custom_fields'] = array('id'=>$key,'value'=>$value);
/*
if you expect multiple id values:
$arr['ticket']['custom_fields'][] = array('id'=>$key,'value'=>$value);
*/
}
}
Your code is processing only $POST keys that start with z. To fix, use this.
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key) || gettype($key) == 'integer'){
$arr[strip_tags($key)] = strip_tags($value);
}
}
I have added || gettype($key) == 'integer' to your if clause to process integer keys as well.

Submit html table data with via form (post)

I want to post this html table on submit button click.
01 - I want to retrieve the data of this table in php code (server side)
02 - I also want to display this table on another page.
I'm using
PHP, JQuery
I have html table with many rows in form tag.
<form id="frm_test" class="form-vertical" method="post">
<table id="mytable">
<tr>
<td>
<input type="text" name="color_1" value="" />
</td>
<td>
<input type="text" name="color_2" value="" />
</td>
<td>
<input type="text" name="color_3" value="" />
</td>
<td>
<input type="text" name="color_4" value="" />
</td>
</tr>
......
......
......
......
.....
</table>
<input type="submit" name="submit" value="submit" />
</form>
===========
there are 4 input fields in each row (4 cells in each row). and hundred rows in table. So if I get value via name in php code then I have to write lot of code to get 100(rows) * 4 (input fields) = 400 inputs. So my question was "What is the best way to achieve this"
Since you are trying to submit multiple rows of inputs/selects with the same 'name' attribute to a backend, you would need to add square brackets [] to the end of the name value in those inputs (in the table rows).
<form>
<input type="number" name="examplevar" />
<table>
<tr>
<td><input type="text" name="color_1[]" /></td>
<td><input type="text" name="color_2[]" /></td>
</tr>
<tr>
<td><input type="text" name="color_1[]" /></td>
<td><input type="text" name="color_2[]" /></td>
</tr>
<table>
<input type="submit" />
</form>
This tells your browser to create an array for that name property.
In php, read it as $_POST['color_1'][0] and $_POST['color_2'][0], and loop as you'd like.
The brackets are in Phil Bailey's answer, but they are not pointed out.
(Added because a recent search led me to this)
To post a form you need to add the action tag which termines the path to go when the form is submitted
<form id="frm_test" class="form-vertical" name="THE_PHP_FILE_TO_POST.php" method="post">
When you want to POST values you should specify input fields with a certain name. If you only want the table is visible you should use the type hidden so the form will POST data, but the inputs aren't visible.
<tr>
<td>
My value
<input type="hidden" name="myValue" value="My value" />
</td>
</tr>
Once your form is posted you can catch the POST data in that PHP file like this:
//THE_PHP_FILE_TO_POST.php
if(isset($_POST))
{
$myValue = $_POST['myValue']; //Contains the string "My value"
//Do something with your POST
}
EDIT Get all table data
if(isset($_POST))
{
foreach($_POST as $inputName => $inputValue)
{
echo $inputName; //This is the name of an input field
echo $inputValue; //This is the value of the input field
}
}
PHP has a an odd naming convention for for table input fields you need to specify the name for the file as an array. For the following SQL Statement using PDO one processing method.
select id,color_1,color_2,color_3,color_4 from colors;
<?php
// Get data
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_NUM);
reset($results);
echo '<table>';
while (list(, $i = each($results)) {
echo '<tr><td><input type=hidden name="id[]" value="' . $i[0] . '"></td>';
echo '<td><input type=text name="color_1[]" value="' . $i[1] . '"></td>';
echo '<td><input type=text name="color_2[]" value="' . $i[2] . '"></td>';
echo '<td><input type=text name="color_3[]" value="' . $i[3] . '"></td>';
echo '<td><input type=text name="color_4[]" value="' . $i[4] . '"></td>';
echo '</tr>';
}
echo '</table>
?>
Simplified $_POST print_r output for 4 records:
Array ( [[id] => Array ( [0] => 20 [1] => 21 [2] => 44 [3] => 45 )
[color_1] => Array ( [0] =>red [1] =>green [2] =>yellow [3] =>blue )
[color_2] => Array ( [0] =>purple [1] =>orange [2] =>green [3] =>red )
[color_3] => Array ( [0] =>red [1] =>green [2] =>yellow [3] =>blue )
[color_4] => Array ( [0] =>purple [1] =>orange [2] =>green [3] =>red ) )
You need to add input field in your table to post data.
like
<input type="text" name="fieldname" value="" />
If you do not want to display field then you can make field hidden by using type="hidden"
Add action attribute in your form.
Action attribute indicates the url on which your data will be posted.

PHP How to Insert Data Input from a Dynamically-Generated Form

I need assistance in taking the next step in inserting data entered into a dynamically-generated form. I have looked for a number of days at other similar questions and am still missing a piece.
Here is my HTML form (minus error trapping/validations):
<form id="form" name="form" method="post" action="recipeaddsubmit.php">
<table id="myTable">
<tr>
<td width="10%">Amount</td>
<td width="10%">Measure</td>
<td width="35%">Ingredient</td>
</tr>
<tr>
<td valign="top">
<input type="text" name="Amt1" id="Amt1" size="1" />
<input type="text" name="Amt2" id="Amt2" size="1" />
</td>
<td valign="top">
<select name="Measure" id="Measure">
<option>Cup</option>
<option>Ounce</option>
</select>
</td>
<td valign="top">
<input type="text" name="Ing" id="Ing" size="40" />
</td>
</tr>
</table>
<button type="button" onclick="displayResult()">Insert new row</button>
<input type="submit" name="button" id="button" value="Submit" />
</form>
Here is the javascript in my header:
<script>
function displayResult()
{
var table=document.getElementById("myTable");
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
cell1.innerHTML="<input type='text' name='Amt1' id='Amt1' size='1' />
<input type='text' name='Amt2' id='Amt2' size='1' />";
cell2.innerHTML="<select name='Measure' id='Measure'> <option>Cup</option>
<option>Ounce</option></select>";
cell3.innerHTML="<input type='text' name='Ing' id='Ing' size='40' />";
}
</script>
And here is my attempted/partial mysqli insert statement (checkInput is a self-created validation function I have used before without issue):
$amt1 = checkInput($_POST['Amt1']);
$amt2 = checkInput($_POST['Amt2']);
$measure = checkInput($_POST['Measure']);
$ing = checkInput($_POST['Ing']);
$ingAddQuery ="INSERT INTO Ingredient (Amt1, Amt2, Measure, Ing)
VALUES ({$amt1}, {$amt2}, {$measure}, {$ing})";
mysqli_query($mysqli,$ingAddQuery);
if (!mysqli_query($mysqli,$ingAddQuery))
{
die('Error: ' . mysqli_error());
}
What I don't understand is how to incorporate a foreach loop in terms of how to increment for a certain number of rows; I understand the concept but not the application in this case.
Thank you for your assistance!
change the name from amt1 to amt1[] and etcetera...
so
<input type="text" name="Amt1[]" id="Amt1[]" size="1" />
When you submit the form,
$_POST['Amt1']; //is an array
will be an array, so you could do
$Amt1Array = $_POST['Amt1'];
foreach($Amt1Array => $Amt1){
//do stuff here
}
Better yet you can index the array using the js to create names like...
<input type="text" name="Amt1[0]" id="Amt1[0]" size="1" />
<input type="text" name="Amt2[0]" id="Amt2[0]" size="1" />
<input type="text" name="Amt1[1]" id="Amt1[1]" size="1" />
<input type="text" name="Amt2[1]" id="Amt2[1]" size="1" />
Then in the PHP you could
$Amt1Array = $_POST['Amt1'];
$Amt2Array = $_POST['Amt2'];
foreach($Amt1Array as $key => $Amt1Value){
$Amt2Value = $Amt2Array[$key];
//do stuff with rows
}
I have a suggestion.
Why don't u create a hidden input type.
<input type="hidden" name="cellCount" value="0" />
Each time u insert a new row, change value of this hidden field. This will not show on browser. This hidden element will also get submit when u submit form. this can be retrieved on server by $_POST["cellCount"].
Hope this will help u.

PHP post two values in one field, one of which is hidden

Is there a way that I can post two values at the same time from a single field in a table but hide one from the user?
I would like the following form to post the values ID and reason_name when it is submitted but have the user only be able to see (and edit in the text box) the reason_name.
<form name="add_positioning" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table border="1" class="autoTable_pos">
<tr>
<td>Positioning</td><td> </td></tr>
<?
$sql= "SELECT * FROM gradeReason WHERE reason_userID = $user_id AND category = 'positioning' AND current = 1";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="text" name="reason[]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<?
}
?>
<tr>
<td>
<input type="text" name="reason[]" size="25"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Save" name="save_reasons"/>
</td>
</tr>
</table>
</form>
The form POST action so far (basic echo at the moment for my own sanity to check that it posts the values correctly, which it does...)
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $item) {
echo $item.'<br/>';
}
}
This table displays the values that are held in a database but enables the user to add more values by dynamically adding a new row (using JQUERY I haven't included) to the table when they type in an empty one at the bottom and also allows them to edit or delete existing values.
For each value posted I intend to check if the ID value is empty, if it is it means that it is a new value and enter a new record into the database, if it isn't update the existing record in the database with the corresponding ID. I don't have a problem writing that bit, I just can't think how to get the ID value posted as well as the reason_name while keeping ID hidden from the user.
Add the ID to the name attribute of the Text boxes of the reasons loaded from the DB. Leave the other Text boxes added using JQ without the ID.
E.g.
Text box which shows the existing reason loaded from the DB
<input type="text" name="reason[][ID]" size="25"/>
Text box added with JQ
<input type="text" name="reason[]" size="25"/>
Then once you submit the form you get you will get the following array.
array
'reason' =>
array
0 =>
array
14 => string 'VAL1' (length=4)
1 => string 'VAL2' (length=5)
By checking for an array in the each element in the "reason" array, you can differentiate two type of Text Boxes.
Here is the complete code I have tested.
<?PHP
//var_dump($_POST);
foreach($_POST['reason'] as $item=>$value)
{
if(is_array($value)){
foreach($value as $ID=>$reason)
{
echo "Existing Reason : ".$ID." - ".$reason."<br>";
}
}
else{
echo "New Reason : ".$item." - ".$value.'<br/>';
}
}
?>
<form action="" method="POST">
<input type="text" name="reason[][14]" size="25" value="aaaa"/>
<input type="text" name="reason[]" size="25" value="bbbbb"/>
<input name="" type="submit">
</form>
Assuming the id is at $row['reason_id'] I think you want:
$i = 0;
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="hidden" name="reason_id[<? echo $i; ?>]" size="25" value="<? echo $row['reason_id']; ?>"/>
<input type="text" name="reason[<? echo $i; ?>]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/></td></tr>
<? $i++ } ?>
This way you can later
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $key => $item) {
$id = $_POST['reason_id'][$key];
echo $id . " " . $item.'<br/>';
}
}

Trouble with dynamic form values with PHP

I have a loop in a form for dynamically adding/removing items, however, only the last item is removed every time. I can add items just fine though.
I can't figure out why no matter which items I try to remove from both add_friends and register_tasks, ONLY the last item is removed. When I echo $_POST['task_name'] it's always the last item on the list, never the one I selected(unless of course I select the last item).
Here is the form
<center><h2>Create Event</h2></center>
<form method="post">
<?
$form = new common_functions();
if($form->check_saved_forms($my_username, "event") == TRUE){
$this->existing_forms(); //allow the user to select existing forms that they have created
}
?>
<tr><td>Title:</td><td><input type="text" width="20%" name="event_title" value="<? echo $form_data[0]; ?>" /></td></tr>
<tr><td>Details:</td><td><input type="text" width="20%" name="event_details" value="<?echo $form_data[1]; ?>" /></td></tr>
<tr><td>Date:</td><td><input type="text" width="20%" name="event_date" id="event_date" value="<? echo $form_data[2]; ?>" /></td></tr>
<tr><td> <input type="submit" name = "submit_event" id = "lOBut" value="Create Event" /></td></tr>
</table>
<?
//this is the section giving me trouble
$form->add_friends($added_friends);
$form->register_tasks($tasks,$nums);
?>
</form>
Both add_friends and register_tasks dynamically add and remove friends/tasks by a textbox, and a list of the added items are shown. users can remove items, however, right now only the last item is removable and I can't figure out why.
Here is register (add_friend is the same, but labeled differently)
function register_tasks($tasks,$nums){
<table>
<td><input type="textbox" size="50" name="register_description"/> </td></tr>
<td><input type ="textBox" name="register_num" /> </td>
<td><input type="submit" name="add_register_tasks" value="Add"/></td></tr>
</table>
<?
if(count($tasks) > 0){
?>
<table>
<tr><td><b>Registration Item Description</b></td><td><b># Of Available Spots</b></td></tr><br>
<?
foreach (array_combine($tasks, $nums) as $task => $task_num){
?>
<tr><td><? echo $task; ?></td><td><? echo $task_num; ?></td>
<td><input type="submit" name="remove_task" value="Remove"/></td>
<td><input type="hidden" name="task_name" value="<? echo $task; ?>"/>
<td><input type="hidden" name="task_num" value="<? echo $task_num; ?>"/></td></tr>
<?
}
?></table><?
}
You need to place the form tag inside the loop. Right now what happens is all the records are displayed in a single form and no matter what item you choose, it takes only the last value. Another alternate solution would be to use GET method and pass the number/name as query string.

Categories