Only last text input array sends to php processing script - php

I am trying to dynamically add fields with jquery for a project. My problem is that when I send the form to the processing script and do a print_r() on the $_POST['item'] it only lists the last array...
Here is my code:
<div class="itemAdd row">
<div class="span4">
<p>Item Number: <br /><input class="span4" type="text" name="item[itemNumber]" /></p>
<p>Status: <br />
<select name="item[status]" class="span4">
<option value="enabled" selected="selected">Enabled</option>
<option value="disabled">Disabled</option>
<option value="damaged">Damaged</option>
</select>
</p>
</div>
<div class="span4">
<p>Item Notes:<br /><textarea class="span4" style="height:100px;" name="item[notes]"></textarea></p>
</div>
<div class="clearfix"></div>
<hr />
</div>
This button adds new fields:
<i class="icon-plus icon-white"></i> Add Item
Here is the jquery to add new fields:
<script>
//Add Items
$('a#addItem').on('click', function(event) {
event.preventDefault();
$('#productItems').append('<div class="itemAdd row"><div class="span4"><p>Item Number: <br /><input class="span4" type="text" name="item[itemNumber]" /></p><p>Status: <br /><select name="item[status]" class="span4"><option value="enabled" selected="selected">Enabled</option><option value="disabled">Disabled</option><option value="damaged">Damaged</option></select></p></div><div class="span4"><p>Item Notes:<br /><textarea class="span4" style="height:100px;" name="item[notes]"></textarea></p></div><div class="clearfix"></div><hr /></div>');
});

You are using arrays in your html, but the index is a string:
item[itemNumber]
So every item will overwrite the previous one.
You could change it to:
itemNumber[]
and
itemNote[]
or, if you have a numeric ID, you could use that.

You're forcing array keys in your form fields, et.c.:
... name="item[itemNumber]" ...
itemNumber isn't a JS var, it's literal html/attribute text in the html blob you're appending. Perhaps you meant something more like
... name="item[' + itemNumber + ']" ...
instead. Even just item[] would allow PHP to assign array keys for you automatically. But as it stands now, PHP will create an array for you, but since all your fields are using the SAME key names, you'll be continually overwriting values and end up with only the last field name/key-pair in the form.

Related

inputs in form created with foreach in PHP, how to pass all input values with post method?

I created a form, where my inputs are created by a foreach loop with data coming from a mysql database.
When the form is submitted with method post, I want to be able to receive all the info through $_POST, but currently I'm only receiving the info from the last created input in the foreach loop.
The variable $fishes comes from mysql database and contains 8 rows, so the foreach loops 8 times.
My goal is to insert this data in a database table, so I can recall it.
When i run my XDebug after pressing submit, my $_POST contains action: insertFish and quantity: (value from input of last iteration in foreach).
I would also like to be able to see the label with the corresponding quantity. I thought by adding a label would work but it didn't.
My form:
<form class="fishadd__form" action="index.php?page=fishtanks&id= <?php echo $_SESSION['tank_id']; ?>" method="post">
<input type="hidden" name="action" value="insertFish">
<div class="fishadd__box--wrapper">
<?php foreach($fishes as $fish): ?>
<div class="fishadd__box">
<h2 class="fish__name"><?php echo $fish ['name']?></h2>
<img class="fish__picture" src="../src/assets/img/goldfish.svg" alt="Goldfish" width="125">
<div class="item__counter">
<div class="fishadd__bottom">
<button class="minus__button">-</button>
<label for="quantity" name="<?php echo $fish['name']?>">
<input class="fishadd__input" type="number" name="quantity" min="0" value="0">
</label>
<button class="plus__button">+</button>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<button type="submit" class="add__fish" value="submit">add to tank</button>
</form>
Thanks to the comments, unique names for the input fields was the fix. I solved it with an array that is looped inside the foreach:
<input class="fishadd__input" type="number" name="<?php echo $fish['name']?>" min="0" value="0">

Dropdown value is not selected on submitting form in php

The scenario is - I have a form with multiple input fields and text areas and whenever I post this form all these values will get posted. However, I also have a dropdown that I create from my database. This dropdown value shows up properly when I get the values. I have a second submit button, which should take this selected value and post to other page.
I have tried the $_POST='name of select option' but it did not help.
I have a onlick for directing the form to other page for updating the db.
I'm fairly new to php, so it could be the use of _POST that could be incorrect.
<form name="f1" class="formoid-solid-blue" method="GET">
<div class="title">
<h2></h2>
<h2>Tracking & Receiving</h2>
</div>
<div class="element-input">
<label class="title"></label>
<div class="item-cont">
<input class="small" type="text" name="store" placeholder="Store #"/>
<span class="icon-place"></span>
</div>
</div>
<div class="element-input">
<label class="title"></label>
<div class="item-cont">
<input class="medium" type="text" name="userid" placeholder="UserId"/>
<span class="icon-place"></span>
</div>
</div>
<div class="element-input">
<label class="title"></label>
<div class="item-cont">
<input class="large" type="text" name="order" placeholder="Order Number"/>
<span class="icon-place"></span>
</div>
</div>
<div class="submit">
<input type="submit" name="Send" value="Send"/>
</div>
<div class="element-separator">
<hr>
<h3 class="section-break-title">Tracking Numbers</h3>
</div>
<div class="element-multiple">
<label class="title"></label>
<div class="item-cont">
<div class="large">
<select data-no-selected="Nothing selected" name="updTR" multiple="multiple">
<option name="op" value="<?php require 'connection.php'; ?>"> //getting value form db
<?php
echo $trackID; //DB value
$trackID = $_GET['updTR']; //getting the variable from the form
?></option>
</select>
<span class="icon-place"></span>
</div>
</div>
</div>
<div class="submit">
<input type="submit" onclick="f1.action='UpdateTR.php'; return true;" name="UpdateTR" value`enter code here`="Submit"/>
</div>
</form>
Well, looking at the form, you said you are using POST, and tested with other POST related method, but your form is using GET, as seen on your code above.
Since you are new to PHP, as an example, if you are using post, and a variable is waiting on the other page to collect this information from your form then you do it like this:
This is the form field example:
<input type="text" name="XYZ">
Then on the page that will collect this info, it would be
$someVariable = $_POST[ 'XYZ' ];
now, if you want to use GET, then its the same thing but you use this
$someVariable = $_GET[ 'XYZ' ];
hope this clears the confusion.
-- EDIT 2 --
Ok after reading your comment, and since i haven't seen how you are iterating through your DB for the options that go in that "option" list/menu, I'm going to say you cant put "connection" as the value on this part:
<option name="op" value="<?php require 'connection.php'; ?>">
because assuming that "connection.php" is connecting to the DB, then that wont help you, that goes elsewhere. Instead, once you've made that connection(elsewhere, preferably above it in the header somewhere), you then have to have code that loops through the DB, and "WHILE" its looping, spit out results into that options field. Let me give you an example with PSEUDO code.
If a normal select/option code looks like this
<select>
<option> option 1 </option>
<option> option 2 </option>
</select>
etc, then you need php that loops through your DB results, and puts the results into the "options" in that select,
here is some pseudo code:
<select>
<?php
while($row = your fetch code here){
echo "<option>your line items here</option>";
}
?>
</select>
OR.....
if "$row" has a specific value you want to use from the database that you visually want to add in that list, then you could do similar to above but with something like:
<select>
<?php
while($row = your fetch code here){
echo "<option>your line items here "' . $row['some value from DB here'] . '"</option>";
}
?>
</select>
etc.
Essentially, you want your "while loop" to iterate through your database and WHILE its doing it, to input its data into your options html.
ALSO, if you wanted a particular value from your DB, put into a GET variable, to use for the processing page (as i mentioned all the way above), then again, similarly, you can do something like this:
<?php
while($row = your fetch code here){
echo "<a href='linkHere.php?yourVariableToTrackWithGetHere='".$row['yourDBresutlToTrack']."'> Your text here </a>"; }
?>
This way, when you click the link, the database value gets added to that variable that you can call later in the processing page.
Kinda long winded but, this should set you 100% straight.
Hope this helps.

How to check a select element change when the element name is an array

What I am trying to achieve:
My form consists of four fields of #item, #unit, #price, and #total.
A user can input multiple lines of #item and #unit. For this, if the user clicks on "Add new line', there will appear a new line to receive user input for item and unit (quantity). If the user clicks on "-" on an already existing line, the line will be removed.
Which item is selected is identified on real-time using javascript change().
The price of the selected item is dynamically retrieved using ajax and the price data is appended into the #price element and #total element is also filled up by calculating #unit x #price.
To achieve this, here's what I did.
First, my HTML form as below.
<form id="form">
<input type="submit" name="create" value="Create" />
<!-- dynamically add more lines -->
<div class="form-group table-row hide" id="template">
<!-- remove button-->
<div class="table-cell" style="width: 45px;">
<a class="btn btn-default removeButton">
<span class="glyphicon glyphicon-minus">
</span>
</a>
</div>
<!-- user input: item -->
<div class="table-cell">
<select id="item" class="form-control">
<option value=""></option>
<option value="item-1">Item 1</option>
<option value="item-2">Item 2</option>
<option value="item-3">Item 3</option>
</select>
</div>
<!-- user input: quantity -->
<div class="table-cell">
<input id="unit" min="1" step="1" value="1" type="number" class="form-control" />
</div>
<!-- price is dynamically filled up using ajax -->
<div class="table-cell">
<input id="price" type="text" class="form-control" />
</div>
<!-- total is dynamically calculated -->
<div class="table-cell">
<input id="total" type="text" class="form-control" />
</div>
</div>
<button type="button" class="btn btn-default addButton">Add new line</button>
</form>
And javascript code to implement dynamic add/remove of input forms.
<script>
jQuery(document).ready(function($) {
var idx = new Number( 0 );
$('#form')
// Add button click handler
.on('click', '.addButton', function() {
var $template = $('#template'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.insertBefore($template);
// assign name attributes with proper array name and index
$clone.find('#item').attr('name', 'lines[' + idx + '][item]').attr('required', 'required').val('');
$clone.find('#unit').attr('name', 'lines[' + idx + '][unit]').attr('required', 'required').val('');
$clone.find('#price').attr('name', 'lines[' + idx + '][price]').attr('required', 'required').val('');
$clone.find('#total').attr('name', 'lines[' + idx + '][total]').val('');
idx = idx + 1;
})
// Remove button click handler
.on('click', '.removeButton', function() {
if (confirm("<?php _e( 'Are you sure you wish to remove this line? This cannot be undone.', 'doumi' ); ?>")) {
var $row = $(this).parents('.form-group');
// Remove element containing the option
$row.remove();
idx = idx - 1;
}
});
});
</script>
Lastly, jQuery to call ajax.
<script>
/* Get Item Price */
jQuery('#item').change(function(){
var $item_id=$('#item').val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// call ajax
jQuery("#price").empty();
jQuery.ajax({
url: ajaxurl,
/* ******************************************************************** */
/* ajax_get_item_price is a function that returns the price of the item */
/* ******************************************************************** */
data:' action=ajax_get_item_price&item_id='+$item_id,
type:'GET',
success:function(results) {
jQuery("#price").append(results);
}
});
});
</script>
I have no problem dynamically adding and removing lines for the input form.
The problem is that form elements in each line is given a name as an array like below;
<select id="item" name="lines[0][item]"></select>
<input id="unit" name="lines[0][unit]" />
<input id="price" name="lines[0][price]" />
<input id="total" name="lines[0][total]" />
<select id="item" name="lines[1][item]"></select>
<input id="unit" name="lines[1][unit]" />
<input id="price" name="lines[1][price]" />
<input id="total" name="lines[1][total]" />
<select id="item" name="lines[2][item]"></select>
<input id="unit" name="lines[2][unit]" />
<input id="price" name="lines[2][price]" />
<input id="total" name="lines[2][total]" />
...
...
...
<select id="item" name="lines[n][item]"></select>
<input id="unit" name="lines[n][unit]" />
<input id="price" name="lines[n][price]" />
<input id="total" name="lines[n][total]" />
I guess that since there are multiple #items with varying names, jQuery does not know which #item it needs to pay attention to. However, I have no idea, either, as to how to properly call ajax with the concerned #item.
Any advice is highly appreciated.
Ok, as I said, ids should be unique for a page, so for similar items you should use classes:
....
<select class="item" name="lines[2][item]"></select>
<input class="unit" name="lines[2][unit]" />
<input class="price" name="lines[2][price]" />
<input class="total" name="lines[2][total]" />
....
So, for change event use something like
jQuery('.item').change(function(){
// to narrow the items, use this
var this$ = $( this );
// this$ contain exactly one item, which is currently changing
// do stuff
});
No quite get what exactly wrong is happening, but I think you have too many items with price is and thus issuing prblems.
So this line does next: gets all #price elements and appends results to each of them.
success:function(results) {
jQuery("#price").append(results);
}
You should clarify which #price item you exactly need.
First, as I already mentioned - use classes for multiple similar fields jQuery(".price")
Second, add some clarification what field exactly should be updated.
There can be many ways, I show two
One way, use next function.
success:function(results) {
this$.next('.price').eq(0).append(results);
// here we refer to this$ - we try to find all `.price` element
// which come after our `select`
// as there can be a lot of them we take only the first one
}
Another way, Use kind of context, ie some div, in bounds of which your elements are grouped.
I suggest changing your html like this
<div class="item-wrapper">
<select class="item" name="lines[2][item]"></select>
<input class="unit" name="lines[2][unit]" />
<input class="price" name="lines[2][price]" />
<input class="total" name="lines[2][total]" />
</div>
So, every block of your fields will be wrapped in a div.
After that we can tell jQUery to find .price element only in a div in which changed select is located
success:function(results) {
var parent$ = this$.parent();
// again we refer to this$ getting its parent which is div
parent$.find('.price').append(results);
// here we try to find `.price` element located in a parent$ div.
// As it is definitely only one, we don't need to use any other code.
}
So, this is all that I can say)

Counting total number of POSTs in controller

A bit of background: I am building an transportation system for a school. The admin can add the places to configure the route. I have a just gave a text box to add a place and ADD button to keep adding more text boxes so he can add multiple places at once.
The problem: The user fills the data, if he wish he adds as many as input boxes he needs and sends that to controller. How can i find out, how many he added the place. I can not use JavaScript Validation because of few reason.
I am using php-codeigniter
<div class="control-group">
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Enter Place/Stop</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span10" id="field1" name="place_6" type="text" data-items="8"/><button id="b1" class="btn btn-info add-more" type="button">Add more</button>
</div>
<br>
<small>Press button to add another place</small>
</div>
</div>
</div>
And the jQuery
$(document).ready(function(){
var next = 1;
$(".add-more").click(function(e){
e.preventDefault();
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span10" id="field' + next + '" name="place_' + (next+5) + '" type="text">';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
});
});
Make sure that new and existing inputs are given the name with an ending "[]" instead of a digit and you will get an array inside your $_POST.
This:
<input type="text" name="places[]" />
Would give you:
$_POST['places']; # array() with all posted inputs
And from there you could just do a count().
count($_POST['places']);

Reply Comment System

Hello Everyone I am new to php and doing a project. My Problem is I am working on review page and fetching data from 3 tables using while loop.
The problem is I want to create comment reply system. I am using text area for comment in loop and showing the text area on button click but when I am click on button, each text area gets visible which I don't want. I think problem is due to while loop.
Please suggest me a proper idea.
Thank u in advance.
Php part:
<div class="feedback-list">
<!--img class="doc-img"src="img/doc-img.png" alt="tempimg" height="100" width="100"/>
<div class="feedback-header"-->
<?php
while($row1=mysql_fetch_array($result1))
{
$username1=$row1['username'];
$rtitle=$row1['reviewtitle'];
$rexperience=$row1['experience'];
echo '<div class="feedback"><img class="doc-img" src="img/doc-img.png" alt="temp img" height="100" width="100"/><div class="feedback-header">Rivew by '.$username1.'
<span class="stars" id="star1"><img src="img/stars.png"/></span>
</div>
<p> '.$rtitle.'</p><br/>
<p> '.$rexperience.'</p>
<form action="submitcomment.php" method="post" name="frms">
<!--button type="submit" onclick="showCommentBox()">Reply</button><br/-->
<input type="button" value="Reply" onclick="showCommentBox('.$row1['reviewid'].')"><br/>
<div class="hidden" id="comment">
<!--p>Comments and suggestions:<br><textarea name="comments" rows="3" cols="30" ></textarea><br><br>
<input type="submit" name="sub" value="Confirm"></p-->
</div>
</form>
<span class="read-more">Read More</span>
<span class="added-by">added on 25 March</span>
</div>';}?>
Script:
<script type="text/javascript">
function showCommentBox(x){
//alert(x);
var div=document.getElementById('comment');
div.className='visible';
document.getElementById("comment").innerHTML =
'<br/><textarea maxlength="5000" cols="30" rows="3" name="comments"></textarea>' +
'<input type="submit" name="sub" value="Confirm">';
}
</script>
ALL of your comment boxes have the same DOM ID:
<div class="hidden" id="comment">
^^^^^^^^^^^^
This is not permitted. An ID must be unique across the entire page. Because of this, getElementById() will only ever return ONE element which matches, which is generally the FIRST matching element it finds - there is no point in continuing to search for something of which only one can exist, right?
You probably want something more like
<div class="hidden" id="comment{$id}">
<button onclick="showComment($id);" >
function showComment(id) {
foo = document.getElementById('comment' + id);
}

Categories