save PHP form data without submit on page refresh - php

I have two forms in the page one is filter, second is the item list, when I apply the filter to item list form, selected values reset to default. For filter I can save selected values, because I submit this form via POST method, but other remains not submited is possible to save selected that form values after page refresh? Here is some code of second form:
<form name="forma" method="post" onMouseOver="kaina();" onSubmit="return tikrinimas()" action="pagrindinis.php?page=generuoti.php">
<table width="540" border="1" align="center">
<tr>
<td>Client:</td>
<td>MB:</td>
<td>Price:</td>
</tr>
<tr>
<td>
<?php
$query="SELECT name,surname,pers_code FROM Clients";
mysql_query("SET NAMES 'UTF8'");
$result = mysql_query ($query);
echo "<select name=Clients id='clients'>";
echo "<OPTION value=''>- Choose -</OPTION>\n";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
echo "</select>";
?></td>
</tr>
</form>

You need to set the selected attribute of your select element based on what is in $_POST. Something like:
$selected = $_POST['Client'];
while($nt=mysql_fetch_array($result)){
if ($selected == $nt[pers_code]) {
echo "<option value=$nt[pers_code] selected="selected">$nt[name] $nt[surname]</option>";
}
else {
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
}
Also note that you should probably sanitize any values you get from $_POST.

Unfortunately there is no easy way to do this, and it's something that PHP and web developers in general have maligned for years, because repopulating form fields is never easy AND clean.
Values in the form you aren't submitting wont be sent (via GET or POST), so you're left with writing a custom workaround.
While it's a bit Q&D, I would recommend sending an Ajax call on form submit to store the values for your second form in the $_SESSION variable.
I'm sorry to say there's no easy alternative - due to the stateless nature of HTTP requests, this is something that every programmer has to struggle with.

just to break the question down to a more simplified form, let's assume we don't have the hassle of working with dropdowns. The real issue you're having is to take a value from form 1 and have it work even after form 2 has been submitted.
If you use a hidden field on form 2, of the same name as form 1, and populate it based on both form 1 and form 2's POST data, it will be "remembered"
<? // mostly html with a bit of php. ?>
<form id="f1" method="POST">
<input type ="text" name="f1val" value="<?= htmlspecialchars( array_key_exists( 'f1val', $_POST )?$_POST['f1val']:'' ); ?>">
<input type="submit">
</form>
<form id="f2" method="POST">
<input type="hidden" name="f1val" value="<?= htmlspecialchars( array_key_exists( 'f1val', $_POST )?$_POST['f1val']:'' ); ?>">
<input type ="text" name="f2val" value="<?= htmlspecialchars( array_key_exists( 'f2val', $_POST )?$_POST['f2val']:'' ); ?>">
<input type="submit">
</form>

<script type="text/javascript" src="js/jquery1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#forma").submit(function(event) {
var 1stformfield = $form.find( 'input[name="misc"]' ).val();
/* stop form from submitting normally */
//event.preventDefault();
$.post("1stformsubmit.php", $("#forma").serialize());
//after it posts you can have it do whatever
//just post code here
$('#iframe1').attr('src', 'iframepage.php?client=' + 1stformfield);
window.frames["iframe1"].location.reload();
return false;
});
});
</script>
<form name="1stform" method="post" action="/">
<input type="text" name="misc" id="misc" />
<input type="submit" name="submit" id="submit" value="submit 1st form"/>
</form>
<iframe id="iframe1" src="" scrolling="no" ></iframe>
iframe page
<form name="forma" method="post" onmouseover="kaina();" action="/">
<table width="540" border="1" align="center">
<tr>
<td>Client:</td>
<td>MB:</td>
<td>Price:</td>
</tr>
<tr>
<td>
<?php
$selected = $_GET['Client'];
$query="SELECT name,surname,pers_code FROM Clients";
mysql_query("SET NAMES 'UTF8'");
$result = mysql_query ($query);
echo "<select name=Clients id='clients'>";
echo "<OPTION value=''>- Choose -</OPTION>\n";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
echo "</select>"; ?></td>
</tr>
</form>
This will post all inputs inside your form to the file you specify then you can have it do whatever you like, for example show a thank you message..Hope it helps.

Related

Delete data from database using php and sql

So I have a php page that looks like this
<?php
echo "<table border='1' width= 300px >
<tr>
<th>Friend Names</th>
<th>Remove Friends</th>
</tr>";
while($row = mysqli_fetch_assoc($result2))
{
$friend_id_got = $row['friend_id2'];
$query3 = "SELECT profile_name
from friends
where friend_id = '$friend_id_got' ";
$result3 = $conn->query($query3);
$final3 = mysqli_fetch_assoc($result3);
echo "<tr>";
echo "<td>" . $final3['profile_name'] . "</td>";
echo "<td>"
?>
<form action="friendlist.php" method= "POST">
<button id="add-friend-btn" type= 'submit' name = 'submit'>Unfriend</button>
</form>
<?php
"</td>";
echo "</tr>";
}
echo "</table>";
When I press the button, I need the corresponding name to delete it. The only problem I'm facing is that How do I get the name corresponding to the button.
I think we need to relate the buttons and the name somehow, so when a specific button is pressed i get the corresponding name
From the question and comments, and a glance at your code it sounds like you probably actually need two pieces of data to be submitted to the server when your button is clicked:
The action which should be undertaken in response to the request (i.e. unfriending)
The ID of the person being unfriended
To achieve that you can add some hidden fields to your form. These are invisible to the user but will be available to PHP in the $_POST data when the form is submitted.
Something like this:
<form action="friendlist.php" method= "POST">
<input type="hidden" name="unfriend_id" value="<?=$friend_id_got ?>" />
<input type="hidden" name="action" value="unfriend" />
<button id="add-friend-btn" type="submit" name= "submit">Unfriend</button>
</form>
Following on from the comment from #ADyson:
<form action="friendlist.php" method= "POST">
<input type="hidden" name="cancel_id" value="<?=$friend_id_got ?>" />
<button id="add-friend-btn" type="submit" name="submit">Unfriend</button>
</form>
By including a hidden field in the form, you're able to store more information.
You can see that I'm storing the ID of the friend you're unfriending in the value of the hidden field, so when the form is submitted (the button is clicked) you'll have access to "cancel_id" in the POST data, which will obviously contain the ID of the friend to unfriend.

Pass select dropdown value outside foreach loop as a $_GET request in form action field

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"

reload multiple table cells with jQuery

I have many forms in a page, each form with several inputs. When you click Submit on a form (say Form0), inputs are send to Reassign.php,that perform a search in a DB according to user inputs, and then a cell with div id="Cell0" in a table of the page is reloaded with data echoed by Reassign.php.
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var MyVariables = $(this).serialize();
$('#Cell00').load('Reassign.php?MyVariables=' + MyVariables);
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var MyVariables = $(this).serialize();
$('#Cell10').load('Reassign.php?MyVariables=' + MyVariables);
return false;
});
});
</script>
A stripped down version of the table:
<table>
<tr>
<td><div id="Cell00"><img src="Image0.jpg"/></div></td>
<td><div id="Cell01">Text1</div></td>
<td><div id="Cell02">Price1</div></td>
<td><div>
<form name="Form0" id="Form0">
<input type="hidden" name="Qst" value="0">
<input type="image" src="ReloadRed.gif" alt="Submit"/>
<select name="cmb1"><option>cmb1Option1</option><option>cmb1Option2</option></select>
<select name="cmb2"><option>cmb2Option1</option><option>cmb2Option1</option></select>
</form>
</div>
</td>
</tr>
<tr>
<td><div id="Cell10"><img src="Image0.jpg"/></div></td>
<td><div id="Cell11">Text1</div></td>
<td><div id="Cell12">Price1</div></td>
<td><div>
<form name="Form1" id="Form1">
<input type="hidden" name="Qst" value="0">
<input type="image" src="ReloadRed.gif" alt="Submit"/>
<select name="cmb1"><option>cmb1Option1</option><option>cmb1Option2</option></select>
<select name="cmb2"><option>cmb2Option1</option><option>cmb2Option1</option></select>
</form>
</div>
</td>
</tr>
</table>
A sample Reassign.php:
<?php
session_start();
$MyVariables = $_GET['MyVariables '];
$cmb1 = $_GET['cmb1'];
$cmb2 = $_GET['cmb2'];
$cmb3 = $_GET['cmb3'];
parse_str($MyVariables);
$Preg=$MyVariables;
$link = mysql_connect("localhost", usr, pswrd) or die(mysql_error());
#mysql_select_db("MyDB") or die( "Unable to select database");
mysql_query ("SET NAMES 'utf8'");
$query = "SELECT Img FROM MyTable WHERE Column1=$cmb1 AND Column2=cmb2";
if($success = mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$image="../ImageFolder/".$row[0].".png";
}
}
echo "<img src=\"".$image."\" />";
?>
This is OK.
Now I want other cells in the table to change as well, but with different (and related) data. Indeed, in the DB seach by Reassign.php, $row[0] is echoed (and thus loaded) in Cell00, and I want $row[1] to be send to Cell01, $row[2] to Cell02 and so on.
My problem is that right now I'm loading Cell0 echoing their content. I think i could do the job calling different php (Reassign0.php to echo data to Cell00, Reassign1.php to echo data to Cell01) but seems rather odd. Any ideas?
Here is a better approach... You can echo JSON instead of HTML from you PHP script, with all fields of the row. (Other code must be put in place for this to work for you, I'll let you research it on your own)
echo json_encode($row);
In your JS, get that json with $.getJSON(url, callback) or $.get(url, callback) depending on your server configuration
Then, loop through the cells and inject the data in your callback
$.getJSON('Reassign.php?MyVariables='+MyVariables, function(row){
for(i=0;i<row.length;i++){
$("#Cell0"+i).html(row[i]);
}
});
EDIT: if you data is not already formatted as HTML (like for images), be sure to do it in your callback. For example, if the first element is always an image URL and the rest is plain data, you can do :
$.getJSON('Reassign.php?MyVariables='+MyVariables, function(row){
for(i=0;i<row.length;i++){
var content = ( i == 0 ) ? '<img src="'+row[i]+'" alt="" />' : row[i];
$("#Cell0"+i).html(content);
}
});

why if (isset($_POST['accept'])) not working?

i have small problem and i don't see any mistakes in my code and server also don't returns any errors but clouse if (isset($_POST['accept'])) doesn't recognize that button was clicked.And is it some way to get value of button id?Please Help.
include '../../config.php';
db_connect();
$zapytanie = "SELECT * FROM messages ORDER BY message_id DESC";
$r = mysql_query ($zapytanie) or die(mysql_error());
$war="L".$_SESSION['lekarz_id'];
echo $war;
if (isset($_POST['accept']))
{
echo "something";
}
else{
while ($row = mysql_fetch_array ($r))
{
if($war == $row['message_recipient'] AND !$row['message_title']=='LP' ){
echo $war;
print "<table border=2 width=98% align=center>
<tr><td><font size=1><p align=left>Od: {$row['message_recipient']}</td> <td><p align=right>Wysłana: {$row['date_of_posting']}</align></font></td></tr>
<tr><td><p align=left><font size=1>Do:{$row['message_sender']}</td><td><b><p align=right>Temat:{$row['message_title']}</align></b></td></tr>
<tr><td colspan=2><br /> {$row['message_text']}</align></font></td></tr>
</table><hr />";
}
else if($war == $row['message_recipient'] AND $row['message_title']=='LP'){
echo "
<form>
<table border=2 width=80%>
<tr>
<td>Od:Wysłana: {$row['date_of_posting']}</td>
<td><p align=center>Wysłana: {$row['date_of_posting']}</align></font></td>
</tr>
<tr>
<td><p align=center><font size=5>Do:{$row['message_sender']}</td><td><b><p align=right>Temat:{$row['message_title']}</align></b>
</td>
</tr>
<tr>
<td ><br /> <font size=5>{$row['message_text']}</align></font>
</td>
</tr>
<tr>";
$id = $row['message_sender'];
$id=substr($id, -1);
print'
<td>
<form action="messages.php" method="post">
<input type="submit" name="accept" value="accept" id=.{$id}./>
</form>
</td>
<td> </td>
</tr>
</table>
</form><hr />
';
}
}
db_close($db);
}
?>
You didn't explicitly set the form action to POST. As a result your form values willbe sent via GET.
Change:
<form>
to
<form method="POST">
Or look for for your value in the $_GET superglobal.
if (isset($_GET['accept']))
You also have a form embedded within a second form. Removing the outer form would also solve your problem.
Check for $_REQUEST['accept']. This combines $_GET, $_POST and $_COOKIE. It will contain the form value regardless of submission method.
http://www.php.net/manual/en/reserved.variables.request.php
I also have to mention, that it's not a good idea to use submit button value to send parameter. What if you need to write "Accept" instead of "accept" on your button?
if ($_POST['accept']=='accept') will fail for such button. Better practice is to use hidden field with name="accept" (<input type="hidden" name="accept" value="any_value" />) and let submit button to do what it has to do - to submit form.
Also it makes your form reusable
phpfidle

getting values from table when checkbox is checked php

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.

Categories