I would like to know how we can store the value selected in an auto populated drop down (HTML5) into a variable, all in PHP. I want to obtain this value BEFORE clicking the 'Submit' button.
<?php
$i=1;
$j=0;
$result=pg_exec($pgsql_conn,"select * from crm.product_info order by 1");
while ($row = pg_fetch_assoc($result))
{
?>
<td><input type="checkbox"
id= <?php
echo $row['product_id'];
?>
value= <?php
echo $i;
?>
name= "prod[]">
<?php echo $row['product_name']; ?>
</td>
<td>
<input type="button" value=<?php echo "$".$row['product_value']; ?> id="but">
</td>
<td>
Quantity
<select class="select" name="qty[]">
<?php echo "qty".$j; ?>
</select>
</td>
<td>
Amount
<input
id="amt"
type="text"
readonly
value=<?php
echo $row['product_value']
?> >
</td>
<?php
}
?>
I require the SELECTED value of 'quantity'.
This is how i auto populate the quantity. It is from 0-100.
$(document).ready(function() {
for(i=0;i<=100;i++)
{
$(".select").append("<option value=\""+i+"\">"+i+"</option>");
}
});
First of all, PHP is server side, so it can't handle changes made in the browser until a request is send to it. You will have to use javascript to know selected value in real time before submitting the form. You can manipulate this value using javascript. But if you really need to do some PHP with the selected value, your solution is to use Ajax for this.
Related
I have a html table displayed using foreach loop in php. And I do even have buttons to be clicked in multiple rows. And the code goes like this:
<form method="post">
<table>
<tr> <th> Item </th> <th>Click to select</th></tr>
<?php
$query="select items from items_table";
$result=$con->query($query); //$con is connection variable already initialized
$row=mysqli_fetch_assoc($result);
foreach ($row as $index) //loop
{
?>
<tr>
<td><?php echo $index['items']; ?> </td>
<td><input type="button" value="select"> </td> //button here
</tr>
<?php } ?>
</table>
</form>
Now how can I get to know which button was pressed?
I have read some web pages, which says we need to be using AJAX, and I'm a newbie with no knowledge of how it works.. Please help me out!
I tried to have button inside a loop and expected that the buttons works correctly directly. But it gives wrong output.
If I got what u want I'd say you should handle your button or input
Some ways available
$index['items']
Is Not Correct where u used
<input value=<?php echo $row['id'] ?>
<input name=foo[<?php echo $row['id'] ?>] value=<?php echo $row['id'] ?> >
<input name='foo[]' value=<?php echo $row['id'] ?> >
Then handle them :
<?php
foreach($_REQUEST['foo'] as $name =>
$value){
echo $name ."posted and its value
is:". $value;
}
?>
OR
<?php
echo 'value of foo[1] Is '.$_REQUEST['foo[1]'] ;
?>
You can use FOR EXAMPLE $row['name'] Or any field name u have in your table intead of $row['id'] that I gave
My code is running a cycle that adds textareas where the user can input queries, which the div it is in also contains a dropdown with a list of servers available to run those queries in. At first it was working just fine for only the first iteration and not showing the list at all in the next dropdowns, but while I was messing with the code and pasted the query inside the cycle all dropdowns were filled but the server ID of the first textarea stopped being posted correctly, instead sending the value that's currently in the database. By other words it won't update properly.
<?php
if(mysqli_num_rows($result_query) > 0){
while($rowq = mysqli_fetch_assoc($result_query)){
$sql_servers = "SELECT id, name, address FROM servers ORDER BY id ASC";
$result_servers = mysqli_query($link, $sql_servers);
?>
<table>
<form name="formStep" method="post" action="">
<br>
<tr>
<textarea class="form-control scrollabletextbox" id="query<?php echo $rowq['step']?>" name="query<?php echo $rowq['step']?>"><?php echo $rowq['query'];?></textarea>
</tr>
<tr>
<td width="25%" style="vertical-align:middle;"><select id="server" name="server" class="form-control input-md">
<?php
if (mysqli_num_rows($result_servers) > 0) {
while($rows = mysqli_fetch_assoc($result_servers)){ ?>
<option value="<?php echo $rows["id"];?>" <?php if($rows['id']==$row_query2['id_server']) echo 'selected=\"selected\"' ?> ><?php echo $rows["name"];?></option>
<?php
}
}?>
</select>
</td>
<td style="padding:10px;"><input type="submit" name="submit" formaction="save.php?i=4&id=<?php echo $id; ?>&s=<?php echo $rowq['step'];?>" class="btn btn-block btn-primary" value="<?php echo $lableSave; ?>"></td>
</tr>
<?php
}
}?>
</form>
</table>
If I echo the server variable in the save.php it will not update for the new selected value in the dropdown, but it will work for all the subsequent iterations of the cycle.
Any way to solve this problem or the previous one before i started trying to hammer the code until it worked would be greatly appreciated.
I am using a form having select dropdown. I want to pass the value obtained from the selected option as a $_GET request in form action field but any ways to access it outside the foreach loop. Here is the code sample that I have written
<form id="dynamicForm" action="client-detail-dynamic.php?id=<?php echo $_GET['id']; ?>&r_id=<?php **PASS THE DROPDOWN VALUE ID HERE** ?>" method="post">
<select class="form-control" id="dynamicfy" name="dynamicfy">
<?php
$j = 0;
foreach($payment_data as $pd):
?>
<option value="<?php echo $payment_data[$j]->r_id; ?>"><?php echo $payment_data[$j]->fy; ?></option>
<?php $j++; endforeach; ?>
</select>
</td>
<td class="col-md-4">
<input type="submit" name="submit" id="submit" class="btn btn-sm btn-success">
</td>
</form>
NOTE: $payment_data is an array containing the table data with field names r_id, fy etc
I have two methods for this.
First method
Create a hidden field inside form element to store the value of id.Put form action null
<form id="dynamicForm" action="" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
On submit you will get two values
if(isset($_POST['submit'])){
$id=$_POST['id'];
$r_id=$_POST['dynamicfy'];
header("location: client-detail-dynamic.php?id=" . $id . "&r_id=" . $r_id . "");
exit();
}
Second method use javascript
<select class="form-control" id="dynamicfy" name="dynamicfy" onchange="rdrt(this.value)">
<script>
function rdrt(str){
id=<?php echo $_GET['id']; ?>;
if(str!=""){
location.href="client-detail-dynamic.php?id=" + id + "&r_id=" + str;
}
}
</script>
Rather than changing the page from FORM ACTION what you can do is pick the values and set them in url passed to header:location.
try this.
``<?php
if(isset($_POST['submit'])
{
$option = $_POST['dynamicfy'];
$id = $_POST['id']
header('location: http://client-detail-dynamic.php?id=$id,r_id=$option');
}
?>
<form id="dynamicForm" action="" method="post">
<select class="form-control" id="dynamicfy" name="dynamicfy">
<?php
$j = 0;
foreach($payment_data as $pd):
?>
<option value="<?php echo $payment_data[$j]->r_id; ?>"><?php echo $payment_data[$j]->fy; ?></option>
<?php $j++; endforeach; ?>
</select>
</td>
<td class="col-md-4">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<input type="submit" name="submit" id="submit" class="btn btn-sm btn-success">
" />
</td>
</form>
What you are trying to do is go somewhere based in the $_GET['id]. That's not possible server side as you have to FIRST make the request, then execute code. If your aren't trying to bring form data with you to this URL, then try this suggestion. However forget what I about not possible. you could do something like:
<?php
if(isset($_POST['submit-button'])) {
header("location: file.php?something=" . $_GET['id']);
}
// set the form action to nothing and add this to the same page the form is on
// and you can redirect based on the $_GET['id']
?>
To change value on selection of dropdown, You will need to use a jQuery on change of select box.
Please refer following code for same.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(Document).ready(function() {
jQuery('#dynamicfy').change();
});
jQuery('#dynamicfy').change(function() {
jQuery('#dynamicForm').attr('action', 'client-detail-dynamic.php?id=' +<?php echo $_GET['id']; ?> + '&r_id=' + jQuery(this).val());
});
</script>
if you just want selected dropdown on the action page then You may also get selected dropdown on the action page with using $_POST['dynamicfy'] on action page "client-detail-dynamic.php"
I'm working on a form that uploads an image to a server. The form contains checkboxes and select boxes formatted to a <table>. Each table row contains two columns. The First column iterates through a mysql query that displays a list of items (24 items to be exact) that is paired to a checkbox. The 2nd column iterates through a mysql query that displays list of clients.
What needs to be done are as follows:
When the form gets uploaded (via POST or GET) the checkboxes which only have check gets passed.
convert the subs_id (name parameter for the select box) to an array for easy processing for mysql insert.
Code Below. Thanks in advanced!
<form method="post" enctype="multipart/form-data" action="upload2.php">
Name: <input type="text" name="item_desc" value="">
Show Date: <input type="text" name="upload_date" class="date" size="10"> to <input type="text" name="expiry_date" class="date" size="10">
Item: <input type="file" name="item"> Display Length: <input type="number" value="8" name="show_time" size="3" style="width:50px"> secs
<table class="data-list" width="100%">
<tr>
<td>Widget</td>
<td>Client</td>
</tr>
<?php foreach($instance as $item):?>
<tr>
<td><input type="checkbox" id="checkAll"/> <?php echo $item['name']; ?></td>
<td><select id="selectBox" name="subs_id[]">
<option selected="selected" value="none">Select Client</option>
<?php foreach($subs as $client): ?>
<option value="<?php echo $item['id'] . '-' . $client['id']; ?>" client="<?php echo $client['client_name']; ?>" ><?php echo $client['client_name']; ?></option>
<?php endforeach ?>
</select>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<input type="submit" value="upload">
</form>
<input type="checkbox" id="checkAll" name='client[]' value ="1" /> <?php echo $item['name']; ?>
name and value is missing
1 .Change your checkbox code to
<input type="checkbox" id="checkAll" name="checkId[]" value="<?php echo $item['name']; ?>"/> <?php echo $item['name']; ?>
Here, I am taking name as array checkId[] and value of checkbox value="<?php echo $item['name']; ?>"
This should work for you.
Your select box is fine. There is no need to change it. you can find value of select box by checking index.
I figured it out. What I did was detect when there was a change on the select box and assign the value of the select box to the check box's value.
$(".selectBox").change(function() {
$(this).parent().siblings().children('input').attr('value',$(this).val());
});
then, on the upload2.php, I used the code below to get the value of only the boxes with check
if(!empty($_POST['checkId'])) {
$filename = $this->unique_filename($this->extract_ext( $_FILES["item"]["name"]));
$folder = dirname(__FILE__) . '/items';
move_uploaded_file($_FILES['item']['tmp_name'],"{$folder}/{$filename}");
foreach($_POST['checkId'] as $check) {
//save to db
$split = explode("-",$check);
$subs_id = $this->use_table('clients')->where('client_name like "' . $split[2] . '%"')->where('site_id=' . $split[1])->fetch();
//$subs_id = $this->query('select * from clients where client_name like "Trinoma%" and site_id=1');
//print_r($subs_id[0][id]);
$data = array(
'item_name'=> 'widgets/' . strtolower(get_class($this)) . '/items/' . $filename,
'show_time'=> $_POST['show_time'],
'instance_id'=> $split[0],
'item_desc'=>$_POST['item_desc'],
'subs_id'=> $subs_id[0][id]
);
$this->use_table(TBL_NAME)->insert($data)->execute();
$mid = $this->last_insert_id();
$this->use_table(TBL_SCHED)->insert(array(
'multirotator_id'=>$mid,
'show_from'=>'00:00',
'show_to'=>'23:59',
'upload_date'=>$_POST['upload_date'],
'expiry_date'=>$_POST['expiry_date']
))->execute();
} //end of foreach
} //end of if(!empty($_POST['checkId']))
and voila! working code for me.
I have this code to show my table:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<table cellspacing='0'>
<?php
if(isset($_GET["ordem"])){
if($_GET["ordem"] == 'descendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo "</tr></thead>";
}
elseif($_GET["ordem"] == 'ascendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=descendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação </th>";
echo "<th>Enviar mail</th>";
echo ("</tr></thead>");
}
}
else{
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=ascendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo("</tr></thead>");
}
while($stmt->fetch()){
echo("<tbody>");
echo("<tr><td>$nomeUser</td>");
echo("<td>$email</td>");
echo("<td>$nomeVoucher</td>");
echo("<td>$categoria</td>");
echo("<td>$preco</td>");
echo("<td>$confirmacao</td>");
$content = file_get_contents($file,$filePDF);
echo("<td><INPUT TYPE='checkbox' NAME='mail[]' multiple='yes'></td>");
echo("</tr>");
echo("</tbody>");
}$stmt->close(); ?>
I have a checkbox in my table and I would like to know how can I get the values of each rows from the table when i selected the checkbox. I want to send email when the user selected multiple checkbox.
Thanks
It's possible that the code above is a snippet of a larger page, but if not:
You aren't actually wrapping your input elements in an HTML form tag. Doing so will cause the user agent (presumably a browser) to treat each input tag as something to be submitted to your backend form.
You should wrap the tables in a table element; tbody is a child of a table.
Regardless of the above:
It looks like your PHP code above will render the entire tbody each time the statement fetches a new row, which is a bit weird. I'd assume you only want to render a row containing mail options?
To the best of my knowledge, there is no multiple attribute allowed in a checkbox element. You may be thinking of the select element.
You are not setting a value attribute on your checkbox input tag. If the user actually submits a form, you'll either get a set of empty mail[] variables, or nothing at all, I'm not actually sure which.
Consider the code below: Note that the checkboxes have the same name attribute, but different values.
<form method="post">
<table>
<tbody>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val1" id="mail-val1" />
<label for="mail-val1">Value 1</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val2" id="mail-val2" />
<label for="mail-val2">Value 2</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val3" id="mail-val3" />
<label for="mail-val3">Value 3</label>
</td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>
Given this form, if the user selects all three of the checkboxes and submits, your server will receive a POST request with the payload:
mail[]=val1&mail[]=val2&mail[]=val3
Depending on how PHP parses that response (it's been about a decade since I've dealt with PHP), you'll probably have an array variable accessible to your application:
# mail == ["val1", "val2", "val3" ]
Hope this helps.