I am creating a form that allows the user to supply additional addresses they are located at. I have a drop down that asks "How many additional locations do you have?" based on the number they select I clone the fields "Address, City, State, Zip" and place them directly underneath of each other inside the same form.
What I described above is working but now I am attempting to retrieve the data from these additional fields I added. When the user clicks the submit button the form submits to the same page where I have PHP listening to see if the form has been submitted or not. If it has been submitted I echo the values of the form to the screen.
Now here is the problem. If I leave the dropbox alone so that it is at the default value of "1" fill out the form and click submit I see what I entered. But if I select any other value from the drop down and submit the information from all of the forms I only see the information from the last form and not all of them. Why is this? I have included my code below.
Here is the form :
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional">
<legend>Additional Locations</legend>
<p><label for="Address">Address</label> <input name="Address" type="text" id="Address" /><br /></p>
<p><label for="City">City</label> <input type="text" name="City" id="City" /></p>
<p>
<label for="State">State</label>
<select id="State" name="State">
<option selected="selected">Select your state...</option>
<?php foreach($states as $key=>$value) { ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php } ?>
</select>
</p>
<p><label for="Zip">Zip Code</label><input type="text" name="Zip" maxlength="6" /></p>
<p><label for="Country">Country</label><select id="Country" name="Country">
<option value="US" selected="selected">United States</option>
<option value="CA">Canada</option>
</select></p>
<input type="submit" value="SUBMIT FORM" />
</fieldset>
</div>
</form>
This is how the fields are created based on the dropdown
var cloneIndex = 0,
cloneObj = $('.additional').eq(0);
$(document).on('change', "#NumberOfLocations", function() {
if ( $(this).val() !== "" ) {
for( var x = 2; x < $(this).val(); x++ ) {
$('#AdditionalLocations').append( cloneObj.clone( true ).attr('' ,'data-index', ++cloneIndex) )
}
}
});
This is how I echo the results of the form. It works if I don't create new additional fields based on the drop down.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
var_dump($_POST);
foreach( $_POST as $field ) {
if( is_array( $field ) ) {
foreach( $field as $field2 ) {
echo $field2;
}
} else {
echo $field2;
}
}
}
?>
If I select 2 as the value in the number of locations field this is the html output I get:
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional"></fieldset>
<fieldset name="first" class="additional" data-index="1"></fieldset>
</div>
</form>
Inside the fieldset all of the fields are identical. Why do I not get both fieldsets echoed when I click submit?
UPDATE:
So I changed the names of the second field set by adding a "1" at the end inside the chrome inspector and submitted now I see all of the values I need. So I guess every field in the form has to have a unique name.
your field names should have array notation at the end of their names:
<input type="text" name="City[]" id="City" />
<select id="State" name="State[]">
when php gets these values they will then be in array so you will need to loop over each of the arrays to get the info
for($i=0; $i<count($_POST['City']); $i++){
$city = $_POST['City'][$i];
$state = $_POST['State'][$i];
...
}
There is probably a better way of getting the info out of the arrays, but this is quick and dirty
Related
I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}
I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name
I have a form. In the form I have a drop down menu of peoples names populated from a database. The rest of the form is made up of a few input fields, address, phone, email. This info is also stored in the same database. What I want is when you select a name from the drop down menu the rest of the form fields fill automatically/dynamically with that persons relative data. No refresh, no submit, no go to another page the fields just populate. I think it's an ajax request I need maybe an onChange function on the form but I'm just not sure. Don't want to use jQuery just javascript. I haven't had much success with this and it's driving me mad. Any help would be appreciated. Here is a snippet of my code from the form :
<option value="" selected="selected" class="firstLine">select a name</option>
<?php $query = "SELECT * FROM customers ORDER BY id ASC";
$run = mysqli_query($dbc, $query);
while($row = mysqli_fetch_assoc($run)){
$row['fullname'] = $row['first'].' '.$row['surname'];?>
<option value="<?php echo $row['id'];?>"><?php echo $row['fullname']; ?></option><?php } ?>
</select>
<input type="text" name="address" id="address" value="" disabled="disabled"><br />
<input type="text" name="phone" id="phone" value="" disabled="disabled"><br />
<input type="text" name="email" id="email" value="" disabled="disabled"><br />
An approach I take often is to create a small getData type of service endpoint.
for example in php: *but you could easily do this in c# like I did in the following link.
http://chadcollins.com/json-service-output-from-sql-select-using-c/
create a /services/getData.php file and inside it:
ensure the page only runs if session is authenticated / check authentication
connect to your database and execute the query to the db by passing the sessionUserID into your select.
echo the response in json format
use jquery to handle the ajax (it will be a bit of code do it with native js, but ok if you want.
on the onChange() event in your UI, consider using ajax method to call your services/getData.php script
then using that returned json collection of json data, loop the data and assign the values to your form fields by id.
Notice in my example script how I print out the format needed for a JSON ajax read call. If you want example php code let me know and I can probably pull something together.
This is what you need to do
<option value="" selected="selected" class="firstLine">select a name</option>
<?php $query = "SELECT * FROM customers ORDER BY id ASC";
$run = mysqli_query($dbc, $query);
while($row = mysqli_fetch_assoc($run)){
$row['fullname'] = $row['first'].' '.$row['surname'];?>
<option value="<?php echo $row['id'];?>" onchange="getdata()"><?php echo $row['fullname'];?></option>
<input type="hidden" name="addressinfo" value="<?php echo $row['address']?>">
<input type="hidden" name="phoneno" value="<?php echo $row['phone']?>">
<input type="hidden" name="emailid" value="<?php echo $row['email']?>">
<?php } ?>
</select>
<input type="text" name="address" id="address" value="" disabled="disabled"><br />
<input type="text" name="phone" id="phone" value="" disabled="disabled"><br />
<input type="text" name="email" id="email" value="" disabled="disabled"><br />
now you can use javascript to populate the value to those input boxes
<script>
function myFunction() {
var phone= document.getElementById("phoneno").value;
var address = document.getElementById("addressinfo").value;
var email= document.getElementById("emailid").value;
document.getElementById('phone').value(phone);
document.getElementById('email').value(email);
document.getElementById('address').value(address);
}
</script>
I have a drop down list, and user can select multi options.
So this is part of my code in firtfile.inc
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select name="SearchIn[]" multiple="multiple" onchange="javascript:this.form.Heading.value=this.options[this.selectedIndex].text;" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php
//Loop over the options
for($i=0;$i<sizeof($SearchCriteria);$i++){
?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php
}//!End of looping over search criteria
?>
</select>
<!-- Hidden heading field for search report -->
<input type="hidden" name="Heading" valtue="" />
</div>
in another php file, I have included firstfile.inc, and i want to get the list of options that user has selected from drop down list.
so I have the folloing in the php file to get the selected options.
$Heading = $dat->if_default('Heading', '');
but it only gives me the first option that the user has selected, but I need all of them. How can I get them?
First of all, I highly recommend that you use jQuery, it will make any DOM manipulation a lot easier.
It's not clear what output you expect, but supposing you're expecting a comma separated string like:
Criteria1, Criteria2, Criteria3
You could:
1) Just use PHP to give you that, with something like:
$SearchIn = $_POST["SearchIn"];
$selectedArr = array();
foreach($SearchCriteria as $item) {
if (in_array($item["value"], $SearchIn)) {
$selectedArr[] = $item["display"];
}
}
$criteria = implode(", ", $selectedArr); // will contain: Criteria1, Criteria2, Criteria3
2) If you want to do it on the client and store the values in <input id="heading"/>, you can use jQuery and do this (your HTML would change a little, to include the IDs):
<form action="index.php" method="POST">
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select id="section" name="SearchIn[]" multiple="multiple" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php for($i = 0; $i < sizeof($SearchCriteria); $i++) { ?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php } ?>
</select>
<!-- Hidden heading field for search report -->
<input id="heading" type="hidden" name="Heading" value="" />
</div>
<input type="submit">
</form>
<script>
$('#section').on("change", function() {
selectedArray = new Array();
$(this).find("option:selected:not([disabled])").each(function() {
selectedArray.push(this.text);
});
$("#heading").val(selectedArray.join(", "));
});
</script>
3) For a pure JavaScript solution (use the same HTML as above):
<script>
document.getElementById("section").onchange=function(){
selectedArray = new Array();
for (x = 0; x < this.length; x++) {
if (this[x].selected && !this[x].disabled) {
selectedArray.push(this[x].text);
}
}
document.getElementById("heading").value = selectedArray.join(", ");
};
</script>
I have used the code below elsewhere in my site and it works. For the life of me I can't understand why it doesn't work here. PROBLEM: keeps throwing alert message.
My HTML:
<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
<div class="outerBlue" style="background:white">
<button type="button" id="cancelForm" class="button" title="Cancel">X</button>
<br><br>
<h3>Get involved—join a committee!</h3>
<?php if(empty($name)||empty($email)||empty($workPhone)){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
<label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
<label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
<label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
<hr>
<p class="clear">Please select a committee from the list below</p><br><br>
<select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
<option value="">Select one...</option>
<?php
$sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
}
echo "</select>";?>
<input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
<div class="clear"></div>
<p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
</div>
</form>
My JS:
$("#joinCommitteeForm").submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
alert('All fields are required');
return false;
}
});
What I suspect the problem is here, is that you are testing if $name or $email is empty, but since you never define them, they will always be empty, per PHP empty() docs: "A variable is considered empty if it does not exist or if its value equals FALSE".
To fix that, you'll need to change your PHP if-statement to:
<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
Also, your POST parameter $workPhone doesn't seem to exist in your form. I've changed it to dayPhone here.
The variable $_POST will contain all parameters in the POST request from the form that's submitted.