Send "Button"-ID on Submit - php

I have an PHP page, which contains a form with some different input fields, e. g. day, month, year etc.. The form method is POST, only one non-editable field (The user ID) is sent via GET.
Of course, there is a "Submit"-Button, which triggers the form Action (PHP Script on Server).
The form tags contain a table with empty cells too. Now comes my question:
If the user clicks into one of the table cells, the form should be submitted, but additional to the regular form data the ID of the table cell should be transmitted too (If via POST or GET doesn't matter to me). How can I do that?
//Edit 2:
...
<form method="post" action="<?= DOMAIN?>/.../addUserTimetable.php?uid=<?= $user->getUserID() ?>">
<select id="day" name="day">
...
</select>
...
<input name="yearend" id="yearend" ...>
<button type="submit">...</button>
<table class="bordered">
<tr>
<th>Std.</th>
<th>Montag</th>
<th>Dienstag</th>
<th>Mittwoch</th>
<th>Donnerstag</th>
<th>Freitag</th>
</tr>
<?php
for($i=1; $i<13;$i++) {
echo "<tr>";
echo "<th>".$i. "</th>";
for($j=1;$j<6;$j++) {
echo "<td id='h".$i. "d".$j. "' onclick='???'></td>";
}
echo "</tr>";
}
?>
</table>
</form>
...
The server sided procession is fine, but I haven't got any ideas - even after two hours google - how I could transmit the cell id additionally.

That shouldn't be to hard. Have a look at the following example:
<form>
<input type="text" name="something">
<table>
<tr>
<td><input type="submit" name="cel1">
</tr>
<tr>
<td><input type="submit" name="cel2">
</tr>
<tr>
<td><input type="submit" name="cel13">
</tr>
</table>
<input type="submit" value="save">
</form>
By giving the submit buttons in the table cells a name attribute, that name will also be present as a key on the $_REQUEST. Go ahead and var_dump the $_REQUEST and you'll see you can find out in the backend which button got pushed by checking which key exists.
Note that POST / GET is completely irrelevant here, both will work just the same. And obviously you could apply some css to those buttons to make them transparent and lay them on top of the table cells, so they don't look like buttons, but just "capture" the user's click.
One last side note, are you sure you want to send the userID as a GET parameter? That would be very easy for someone with bad intentions to manipulate. Consider not sending the ID at all, but keeping it in the session on the server.

Related

When submitting this button inside a datatable doesnt submit the right row id

I have a dynamic table which is set inside a foreach, so for each item of the array fetched create a new row. I have in the last column a button for each row. When clicking that submit button I am suppose to receive the id of that in PHP. Submission is being done correctly, but I am receiving the wrong id in PHP. Its basically taking the last id of the array when submitting. Any idea why?
Here is the table:
<form method="post" id="frm-example" action="<?php echo $_SERVER["PHP_SELF"] . '?' . e(http_build_query($_GET)); ?>">
<table id="example" class="display compact">
<thead>
<th>Device</th>
<th>Sales date</th>
<th>Client comments</th>
<th>Breakage count</th>
</thead>
<tbody>
<?php foreach ($arr_cases_devices as $cases) { ?>
<tr>
<td>
<?php echo $cases['name']; ?>
</td>
<td>
<?php echo $cases["sales_date"]; ?>
</td>
<td>
<?php echo $cases["dev_comment"]; ?>
</td>
<td>
<input type="hidden" name="device_id_breakage" value="<?php echo $cases["Dev_Id"]; ?>" />
<button type="submit" name="see_rma">See RMA</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
When clicking on see_rma this is what I receive in PHP:
if (isset($_POST['see_rma'])) {
$selected_dev = e($_POST['device_id_breakage']);
print_r($selected_dev); // prints the "Dev_Id" of the last row, not of the row clicked
}
If I try printing $cases["Dev_Id"]; inside loop in the table, it prints perfectly fine, so it prints the Dev_Id of each row correctly. So, that means there is nothing wrong with the array or data. I don't why is this happening but it's for sure the first time I am having this issue.
I do this in many other tables but for some reasons in this one its not working properly.
You have multiple <input> elements with the same name within your form, and all of them are going to be submitted when you submit the form, but PHP can only get one of them. That's why you end up with only the last one in $_POST.
It looks like you should be able to fix this by just moving some attributes from the hidden input into the button (replacing the hidden input).
<button type="submit" name="device_id_breakage" value="<?php echo $cases["Dev_Id"]; ?>">
See RMA
</button>
Only the button that was clicked will be submitted. Note that after changing the name of the button, you won't have see_rma in $_POST any more, so if you have any code that depends on that you'll need to change it to look for the other name instead.

Can I eliminate use of hidden form fields in html to pass data between pages where the data is row id of all table rows

I am developing an web app in which user should click on a link dislayed next to an order to generate an order details pdf
The page showing the orders by a particular user as a table with two columns:- time of order and pdf link for each order is having this snippet
echo '<table class="table"><tr>
<th>Order Submitted on</th>
<th>Get Details</th>
</tr>';
while ($row = $ordersByUser->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>'.$row['timestamp'].'</td>';
echo '<td><form method="POST" action="generateorderpdf.php">
<input type ="hidden" name="orderid" value='.$row['id'].'>
<input type="submit" value="CLICK" class="btn btn-dark">
</form></td></tr>';
}
echo '</table>';
I am storing the primary key of each order $row['id'] in a hidden field which is then sent to the generateOrderPdf.php page to generate the order pdf through a form using post method. My problem is that users can change the hidden input field using some browser developer tools and generate pdfs for other users which i definity don't want users to do (and its the reason why i am sending post request to the generate pdf page since anyone can edit the get url and see other people's orders). So is there any way in which I can eliminate the dependency on hidden input fields to send order id to the generateOrderPdf.php page?
I've read that i can use sessions to store sensitive data which then eliminates the need to use hidden form fields but I don't know is it even possible to use session variables to solve this problem and if possible how since this is a table of data?
Actually, you can do this with a session variable.
Put all the order IDs in an array in the session. Instead of putting the order ID in the hidden input, put the array index.
$myorders = [];
$order_index = 0;
echo '<table class="table"><tr>
<th>Order Submitted on</th>
<th>Get Details</th>
</tr>';
while ($row = $ordersByUser->fetch(PDO::FETCH_ASSOC)) {
$myorders[$order_index] = $row['id'];
echo '<tr><td>'.$row['timestamp'].'</td>';
echo '<td><form method="POST" action="generateorderpdf.php">
<input type ="hidden" name="orderid" value="'.$order_index.'">
<input type="submit" value="CLICK" class="btn btn-dark">
</form></td></tr>';
$order_index++;
}
echo '</table>';
$_SESSION['myorders'] = $myorders;
Then in generatorderpdf.php, you use $_SESSION['myorders'][$_POST['orderid']] to get the order ID.

Delete button on user panel

i was always curious about how many websites have a delete button on their user panels.
For example, if a user can submit a post and this must be available on his user control panel to delete it if he wants how would you code this button without any frameworks in php?
What i've dont now its creatre a form with a hiden value, you can see a piece of the code below:
<?php foreach ($results as $result): ?>
<tr>
<td> <?php echo $result['id'] ?> </td>
<td> <?php echo $result['message'] ?> </td>
<td> <?php echo $result['name'] ?> </td>
<td>
<form method="POST" action="">
<input type="checkbox"
name="delete_action"
value="<?= $result['id'] ?>"
style="display:none; visibility:hidden;"
checked>
<input class="" type="submit" value="Delete">
</form>
</td>
</tr>
Time for the php action:
if (isset($_POST['delete_action'])) {
$get_id_to_delete = $_POST['delete_action'];
$delete_action = $pdo_testimonials->prepare("DELETE FROM testimonials WHERE id = :id");
$delete_action->bindParam(':id', $get_id_to_delete);
$delete_action->execute();
}
So, as you can see the methond is so insecure and easy to mess up. However i've used it only for a control panel which only i have access. I know that i should never use a similar way of adding a delete button on a production website.
Is there any better, more secure and reliable way to do it?
Simple link (GET) showing only when it's content that current user can remove is ok, as long as you check that in PHP again. So:
Check if current user can remove element.
If so, display (image) link to for example /delete.php?id=2.
On page delete.php check if current user can remove element with id = 2.
If so, remove element and get back to page. Otherwise display warning.
It can be done with AJAX too, with same steps.

While loop form to delete mysql_entry

I have this chunk of code, which is displayed on a user's journal page. They can add an entry and they have the option to delete an entry once it's on the page.
Ill show the code with some comments and then explain the problem.
// Figures out how many recent posts to display
$posts = $config_journalposts + 1;
if($noposts!=1) {
// Gets the data from the query
while(($row = mysql_fetch_array($journalquery)) && ($posts > 1)) {
// For each of the posts that were gathered, display the following:
echo '<table border="0" width="100%">
<tr>
<td colspan="2" style="vertical-align:bottom;">
// Display the title as a link to be used as a permalink
<p class="fontheader">'.$row['title'].'</p>
</td>
</tr>
<tr>
// Show the o-so-important content
<td width="100%" style="vertical-align:top;padding-left:10px;">
'.$row['content'].'
</td>
</tr>
<tr>
// Show the date
<td style="font-size:8pt;padding-top:10px;">'.$row['date_day'].'/'.$row['date_month'].'/'.$row['date_year'].'</td>';
// Checks if the current user is the owner of the journal or an admin
if($_SESSION['user']==$pageowner || $_SESSION['user_rank']=='Admin') {
echo '<td align="right">
// FOCUS POINT
<form method="POST" id="deljournal">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
// A delete button that executes a bit of Javascript
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal()" />Delete</button>
</form>
// END FOCUS POINT
</td>';
}
echo '</tr>
</table>
<hr>
';
$posts --;
}
Here is the Javascript that gets triggered on the button press
function delete_journal() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
// Submits the form
$("#deljournal").submit()
}
}
This javascript triggers the forum in the PHP code above which reloads the page and triggers this at the very top of the page, before the tag
if(($_POST['delete_id'])) {
// Gets the post ID from the hidden forum tag
$deleteid = addslashes(strip_tags($_POST['delete_id']));
// Deletes the row that has the ID of the hidden form
mysql_query("DELETE FROM `gamezoid_accounts`.`journal_$pageowner` WHERE `id`='$deleteid'");
}
Now, for the problem. In the while loop, this form gets repeated over and over. What happens is that upon pressing the delete button, it triggers the form that has the ID "deljournal". Since all of them have the ID "deljournal" it does the one at the top of the page. Trying to embed the post ID into the form ID breaks the code because the mysql_query doesn't know that the delete function has been triggered in the first place.
Any way around this?
Reason why I'm using Javascript as a trigger is for the confirmation popup in case anyone askes.
Anyways, thanks heaps for reading this far!
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
and on server side u should use
$delete_values= implode (',',$_POST['delete_id']);
Found a solution.
I have changed the form to be
<form method="POST" id="deljournal_'.$row['id'].'">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
</form>
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal_'.$row['id'].'()" />Delete</button>
by adding the journal entry ID into the ID of the form and the onClick function. The javascript is just below it outside the table cell and looks like:
<script type="text/javascript">
function delete_journal_'.$row['id'].'() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
$("#deljournal_'.$row['id'].'").submit()
}
}
</script>
where the entry ID has been added to the function name and form ID tag. By putting the Javascript into a while loop and not into an external file, it can be manipulated with the loop to have the same values.
It is a bit messy and will slightly increase load times + execution times but it was the quickest way that I could find.
Hope this helps anyone else who has been having a similar problem.

How to generate a json array from a table data inside a <td> tag

I am trying to get those data in the JSON format. Would you please help me to generate that? Please help I am not very familiar with jquery and php.
html code looks like this
<form>
<table>
<tr>
<td>//some code for other table elements</td><tr>
<tr>
<td>Critical Times (Coverage): </td>
<td rowspan="3" colspan="2">
<div>
<table width="100%" bgcolor="white" border="0px" name="criticalTime" id="criticalTime">
</table>
</div>
</td>
<td>
<input type="button" id="timeAdd" value="+"/><br>
<input type="button" id="timeRemove" value="-"/>
</td>
</tr>
<tr>
<td>//some code for other table elements</td>
</tr>
</table>
</form>
my .js file has the following to handle the addition of rows to the table when click the + button.
var rowCountr = 0;
var timeTable="<thead><tr bgcolor='E1ECFF'><th></th><th align='left'>Start Time</th><th align='left'>End Time</th></tr></thead>";
/* insert the html string*/
$("#criticalTime").html( timeTable );
/*Event for the +(Add) button in critical time table*/
var timeRwcntr=0;
timeRow="<tr><td><input type='checkbox' id='row'</td><td><input type='text' id='start' /></td><td><input type='text' id='end'/></td></tr>";
$('#timeAdd').click(function(){
$('#criticalTime').append(timeRow);
rowCountr++;
timeRwcntr++;
});
$('#timeRemove').click(function(){
$('#criticalTime tr:last-child').remove();
});
When I click the submit button from main form I need to get those values entered in the input fields and generate an JSON array to store those in database. Please help.
For this problem, I think that JSON may be overkill. You're just trying to send your table's input fields back to the server on a postback right? When you create your table rows, add a uniquely identifying number in the "name" attribute of your form controls <input name="'.$id.'_field" /> for example if you are rendering the table server-side; the code would be similar for javascript. Then, when you post back, you can loop through each row by counting and then access the POST variable you got back by referencing the name. Example:
for ($i = 0; $i < $rowcount; $i++) {
$field_value = $_POST[$i.'_field'];
...
}
JSON is great for more complex data sets, but in your case it sounds like you have structured two-dimensional rows and columns.

Categories