PHP get button ID - php

Is it possible to get the button ID? I have accumulated forms and I wanted to get the button clicked using the unique ID. The following scripts I used:
echo("<table><tr>
<td id=\"i\"><img src='presentations/uploaded_files/$name.png' alt='animal' width='50px' height='50px'/></td>
<td id=\"n\">$name</td>
<td id=\"d\">$dsc</td>
<td id=\"t\">$type</td>
<td id=\"g\">$grade</td>
<td id=\"b\">
<form enctype=\"multipart/form-data\" action=\"admin_update_animal.php\" method=\"POST\"><input type=\"submit\" value=\"Update\" name=\"update\" id=\"$name\"/></form></td>
</tr></table>");
I used the following when any of the button clicked:
if (isset($_POST['update'])) {
$f=trim($_POST['update']);
}
But I wanted to get which button clicked using its unique ID assigned.
I am very glad for a help. Thanks.

You cannot directly read the id of a control because name is passed to the server side script via any methods. You can use hidden input fields whose value can be the id of the button. This lets you know the id of the button in the server side.
This can be done as:-
<script type="text/javascript">
function createField(id)
{
var x = document.getElementById("hide");
var y = "<input type='hidden' name='iddetector' value='"+id+"'/>";
x.innerHTML = y;
return;
}
</script>
//maintain other stuffs here and now
<input type="submit" id="uniqueid" name="submit" value="submit"onClick="createField('uniqueid');return true;"/><br>
<div id="hide"></div>
You can detect the id of the button i the sever side as:-
<?php
$idButton = isset($_POST['iddetector'])?$_POST['iddetector']:NULL;
echo "The id of the button clicked is ".$idButton;
?>

What is passed via POST is the name of the control, not the id. To capture the ID you would be better off using JavaScript before submit.
The point is that you may have multiple controls in different places in the page with the same name (but different IDs) that perform the same task (like submit).

Related

Input div id into text box and delete it from a text file when submit is pressed

I have been racking my brain trying to get a very particular function to work. It seems simple but I just cant figure it out. I am looking to basically get a txt file and allow someone to type in a certain id into an input box that upon the user clicking "delete" will remove only the targeted DIV id.
I have tried wrapping a PHP file around a form with no success, as well as putting the PHP directly into the submit button but nothing has worked, can anyone point me in the correct direction?
I have looked for other post here but nothing seems to be exactly what im looking for or I am wording it incorrectly. This is essentially how I want it to look:
<form action='delete.php' method='post'>
<input name='idinput' type='text' value='Enter The Certain ID Value You Want To Remove'>
<input type='submit' name='submit' value='Remove'>
</form>
Not sure about the text file bit but to remove an element from the DOM, well, you can't do this in PHP without reloading the page and apssing in some extra data na dusing some logic to not display that element...
You need to use JavaScript... or with JS with jQuery
$(function(){
$('input[name="submit"]').on('click', function() {
var val = $('input[name="idinput"]').val();
$('#or.IDorCLASSNAME_' + val).remove(); //If Id Input val is 3 this gives #or.IDorCLASSNAME_3
});
});
jQuery: https://api.jquery.com
jQuery Remove: https://api.jquery.com/remove/
jQuery DOM Removal: https://api.jquery.com/category/manipulation/dom-removal/
Tutorial: https://www.w3schools.com/jquery/jquery_dom_remove.asp
I was able to do this by placing a form that is inserted within the txt info im submitting:
<form action='delete.php' method='post'>
<input type='hidden' name='random' id='random' value='".$random."'>
<button type='submit' value='report'></button>
</form>
And also by adding this to the delete.php page:
<?php
$random = $_POST['random'];
$original = "<div id='".$random."'>";
$replacement = "<div id='".$random."' class='hidden'>";
$str = file_get_contents('submissions.txt');
$str = str_replace("$original", "$replacement",$str);
file_put_contents('submissions.txt', $str);
header('Location: index.php');
?>

DOM manipulation - Multiple forms

I have several forms on my page (via a loop), each have it's own submit button.
I want to use AJAX to get and POST the data to a .php. I need to know which form was submitted so I can get the corresponding values.
It's a simple cart application. This form allows a user to change the quantity of the items in the cart before checkout.
You see that there are two "Change Quantity" buttons (sumbit buttons) and these two fields are wrapped in a form tag.
The loop that encloses the form is :
while ($row = $query->fetch_assoc()) {
$item_code = $row['product_id'];
$item_name = $row['name'];
$item_price = $row['price'];
$item_qty = $row['qty'];
print"<tr>
<td>
<img src='http://localhost/store/images/products/$item_code.jpg'>
</td>
<td>$item_code</td>1
<td>$item_name</td>
<td>$$item_price</td>
<td>
<form method='post' action='/store/processing/view_cart.php' class='cart_view_ajax' id='form_id_$item_code'>
<input type='text' maxlength='2' value='$item_qty' id='qty'>
<input type='hidden' value = '$item_code' name='product_id' id='product_id'>
<div><input type='submit' id='submit' value='Change Quantity'></div>
</form>
</td>
<td>x</td>
</tr>";
}
The Question :
How do I know via jQuery that which form was submitted? Help me out...
According the given answers, I've managed to get the Quantity of the submitted form like this by jQuery. Here's the code :
$('form.cart_view_ajax').on('submit', function(e) {
e.preventDefault();
// start working
var form = $(this);
var form_id = form.attr('id');
console.log($('#'+form_id).children().eq(0).val());
return false;
});
You can just use the 'product_id' because it should be unique to each item
<input type='hidden' value = '$item_code' name='product_id' id='product_id'>
Or you can add an unique ID property to the form tag
<form method='post' action='/store/processing/view_cart.php' class='cart_view_ajax' id='item_$item_code'>
$('form#item_3')
You can add an unique id to the row so can manipulate it later on and you can access the form later on.
<tr id="row_$item_code">
$('tr#row_3 form')
You can add 'data' attributes to the form
<form method='post' action='/store/processing/view_cart.php' class='cart_view_ajax' id='item_$item_code' data-form_id="$item_code">
var form_id = $('form#item_3').data('form_id');
Can we see the jQuery code you are currently using?
You may use another hidden input field that contains an identifier for that special form. I think that would be the easiest way to do it.

Get hidden input value from clicked form on page

I have a list of users registered to the application, for the admin there is an option to delete any user registered. I have the list being populated from the database with PHP.
So every one of the users in this list gets a tr row in this table that has all the users in it. At the right column I have a button which only the admin sees on this table of users, and he can delete that specific user by clicking on that 'delete' button.
I would like that before deleting occurs, which is working fine, there should be a pop up alerting to the admin asking "Are you sure you would like to delete "blank" from the system?" with blank having the name of the user the admin clicked the delete button by.
Now I do have the name of the user in a hidden input field attached to the delete button, in other words I am getting a name coming out in that sentence, the problem though is that the same name of the first person on the list is showing up when I click on any one of the delete buttons on the users list. So to clarify although the deleting is happening to the correct user, so it doe's delete the user I would like to delete, the name in the confirmation alert is showing always with the name of the first user.
I believe this is a problem with the way I am writing the jquery code, so any assistance with this would be greatly appreciated, I am sitting on this for a while already trying to find an answer online for this.
So to sum it up in short:
I have a couple of "forms" on the page (i.e. meaning "delete" buttons that causes a "form" with hidden input information of the user that we would like to have deleted, is sent to the back-end in order for the back-end to know which user to delete.)
The delete function is working just fine - deleting the desired user.
However the alert function is not populating the desired message to the admin, since the name of the user in the message doe's not change from user to user, and it's grabbing always the name of the first user on the users list.
Here is the code for the users list:
<table class="table table-striped table-bordered">
<thead class="dark_grey">
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>User Level</th>
<th>Actions</th>
</thead>
<tbody>
<?php
foreach ($user_rows as $row)
{
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td><a href='/ci/user/user_profile/?={$row['id']}'>{$row['first_name']} {$row['last_name']}</a></td>";
echo "<td>{$row['email']}</td>";
echo "<td>{$row['created_at_time']}". " " ."{$row['created_at_date']}</td>";
if($row['user_level'] != '9')
{
$row['user_level'] = 'normal';
echo "<td>{$row['user_level']}</td>";
}
else
{
$row['user_level'] = 'admin';
echo "<td>{$row['user_level']}</td>";
}
echo "<td class='last_td'>
<form class='float_left' action='/ci/user/edit_user' method='post'>
<input type='hidden' name='email' value='{$row['email']}'/>
<input class='btn btn-success' type='submit' value='Edit' />
</form>
**<form class='delete' action='/ci/user/delete_user' method='post'>
<input type='hidden' name='email' value='{$row['email']}'/>
<input type='hidden' name='name' value='{$row['first_name']} {$row['last_name']}' />
<input class='btn btn-danger' type='submit' value='Delete' />
</form>**
</td>";
echo "</tr>";
}
?>
</tbody>
</table>
Here is the jquery code:
<script type="text/javascript">
$(document).ready(function () {
$('.delete').submit(function () {
var name = $('input[name="name"]').val();
alert("Are you sure you would like to delete " + name + " from the system?");
return false; //I just have this here so the delete didn't take place when testing the alert function.
});
});
</script>
So I know somehow I need to have the alert on the current clicked (".delete") but when I tried using $(this) it didn't really work. Very possible I was using it wrong.
If someone can show me the right way to write the jquery to be able to get the current clicked "delete" button's hidden input name value in the message that would be great!
Thanks in advance for your help!
You need to make your selector specific like $(this).find('input[name="name"]').val().
Try:
$('.delete').submit(function(){
var name = $(this).find('input[name="name"]').val();
alert("Are you sure you would like to delete " + name + " from the system?");
return false; //I just have this here so the delete didn't take place when testing the alert function.
});
When you do $('input[name="name"]').val() it matches more than one input name=name so jquery method val() will return the value of only the first element in the collection, and hence the behavior that you are seeing.
here is a snippet from val() from jquery code
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0]; //<--- It just takes first element in the collection
if ( !arguments.length ) {
if ( elem ) {
...........
I think I just finally found an answer to my question:
Here is the jquery code that worked:
<script type="text/javascript">
$(document).ready(function(){
$('.delete').submit(function(){
var name = $(this).find('input[name="name"]').val();
alert("Are you sure you would like to delete " + name + " from the system?");
});
});
</script>
I got the answer after finding this post:
jQuery get value from hidden input in column
Thanks for your help stackoverflow! :)

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 save a javascript rendered countdown timer to mysql using PHP?

can someone please tell me how to save a javascript rendered countdown timer to mysql db using PHP ?
e.g
I have this button, that when someone clicks it, the countdown appears and starts counting.
so yeah, that's my problem, what's the best way to do in order to ensure that
- the exact date/time(in unix format) the button got clicked will be saved in db?
is this possible with PHP ?
// this is the PHP and HTML
<?php foreach($task->result() as $row): ?>
<tr>
<td><a title="<?php echo $row->descr; ?>"
href="#"><?php echo $row->title; ?></a>
</td>
<td><input type = "button"
id =<?php echo $row->title; ?>
value = "Unlocked"
onmouseover = "asktolock(this.id)"
onclick = "lockme(this.id)">
</td>
<td><?php echo $row->assign_to; ?></td>
<td><a id="txt"></a></td>
</tr>
Have your button populate a hidden formfield with a timestamp when it is clicked. Set the form to POST to a PHP script which processes the formfields and stores them where you like.
ETA: So on your form you'll need a field like this (with a unique name) for every timestamp you wish to store:
<input type='hidden' name='mytimestamp_unique' id='mytimestamp_unique' value=''/>
And then you'll add some code to your javascript function to set the value of the corresponding "mytimestamp" field. Something like:
function lockme(id){
//parse the id to get the unique part of the id which is also the unique part of mytimestamp_unique
var $hiddenfield=getElementById('mytimestamp_' + $uniquepart);
$hiddenfield.value=new Date().getTime();
//do other lockme stuff
}

Categories