Delete button and confirmation - php

Hi I have a working link to delete a row from my database.
<strong>Delete this Case</strong></td>
<?php
if($_POST['action']=="delete")
{
$id = $_POST['id'];
mysql_query("DELETE FROM rmstable2 WHERE id= '$id'");
echo("> Case # $id has been deleted as requested. To see your changes please click <a href='/martinupdate.php?id=$id'>here</a></b><br>");
}
?>
what I am looking to do is instead of having a link I want to have a button that when pressed it brings up a confirmation and then deletes the row if true.
I do not want accidental deletions.
<form>
<input type="button" value="Delete this Case" onclick="return confirm('Are you sure you want to delete?')";
<a href="?action=delete&id=<? echo $id ?>">
</form>

Try this at the top of your file:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'DELETE' || ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['_METHOD'] == 'DELETE')) {
$id = (int) $_POST['id'];
$result = mysql_query('DELETE FROM rmstable2 WHERE id='.$id);
if ($result !== false) {
// there's no way to return a 200 response and show a different resource, so redirect instead. 303 means "see other page" and does not indicate that the resource has moved.
header('Location: http://fully-qualified-url/martinupdate.php?id='.$id, true, 303);
exit;
}
}
With this as the form:
<form method="POST" onsubmit="return confirm('Are you sure you want to delete this case?');">
<input type="hidden" name="_METHOD" value="DELETE">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<button type="submit">Delete Case</button>
</form>

you have to put your confirmation in the onSubmit event of the form
so if the user cancel the confirmation, the form won't be sent
<form onSubmit="return confirm('Are you sure you want to delete?')">
<button type="submit" ...>
</form>

HTML:
<form id="delete-<?php echo $id; ?>" action="?action=delete" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" value="Delete this Case" />
</form>
JS im assuming jquery for ease:
$("#delete-<?php echo $id; ?>").submit(function() {
return confirm("Are you sure you want to delete?");
});
What this does is prevent the default submit action if the js confirm returns false (doesn't submit) otherwise lets the regular post go through.
Note: you really shouldn't use html attributes to declare event handlers, this code separates the logic.
EDIT: #Nicholas comment
This is a non-jquery solution. I didn't test it, and i don't believe that preventDefault works in IE <= 8 so I probably wouldn't use it in production BUT it could be done w/o too much code jquery just makes it cross browser and easier.
function loaded()
{
document.getElementById("delete-<?php echo $id; ?>").addEventListener(
"submit",
function(event)
{
if(confirm("Are you sure you want to delete?"))
{
event.preventDefault();
}
return false;
},
false
);
}
window.addEventListener("load", loaded, false);

Related

POST form displaying wrong echo

I'm trying to display one of two buttons depending on "magnum"(printername) being in present in the array "booleans".
My problem is that when the form gets posted, the data retrieved on page load is correct, but the buttons displayed are incorrect. if clicked on a button, the form posts and refreshes the page, "magnum" gets pushed into $_SESSION['booleans'] but the button still displays "btn btn-default", so it requires another page refresh for the button to load correctly('btn btn-succes').
Is my problem due to $_SESSION or am i missing something?
echo'
<form class="form1" method="post" action="" id="form1">
<div class="col-xs-offset-1 col-xs-2">';
if(in_array('magnum', $_SESSION['printers'])){
if(in_array('magnumBool',$_SESSION['booleans'])){
echo '<input type="submit" name="unSubmitMagnum" id="magnumBool" value="magnum" class='.$enabled_printer.'>';
if(isset($_POST['unSubmitMagnum']) && $_POST['unSubmitMagnum']){
$pos = array_search('magnumBool', $_SESSION['booleans']);
unset($_SESSION['booleans'][$pos]);
dump('unset');
}
}
elseif(!in_array('magnumBool',$_SESSION['booleans'])){
echo '<input type="submit" name="submitMagnum" id="magnumBool" value="magnum" class='.$disabled_printer.'>';
if(isset($_POST['submitMagnum'])&& $_POST['submitMagnum']){
array_push($_SESSION['booleans'],'magnumBool');
dump('set');
}
}
}
else{
echo '<button id="magnum" class='.$lost_connection_printer.'>1. Magnum</button>';
}
echo '
</div>
</form>';
$_SESSION['printers'] is an array containing "magnum" -
$_SESSION['booleans'] is the array which isn't working as i would like it to -
$enabled_printer = "btn btn-success" <br>
$disabled_printer = "btn btn-default" <br>
$lost_connection_printer = "btn btn-danger disabled"
The problem is that you are mixing elaboration and printing. Try to split you code, so it will work and it will be more readable:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['unSubmitMagnum']) && $_POST['unSubmitMagnum']) {
$pos = array_search('magnumBool', $_SESSION['booleans']);
unset($_SESSION['booleans']['magnumBool']);
} elseif (isset($_POST['submitMagnum'])&& $_POST['submitMagnum']) {
$_SESSION['booleans']['magnumBool'] = true;
}
}
echo'<form class="form1" method="post" action="" id="form1">
<div class="col-xs-offset-1 col-xs-2">';
if(in_array('magnum', $_SESSION['printers'])){
if(isset($_SESSION['booleans']['magnumBool'])){
echo '<input type="submit" name="unSubmitMagnum" id="magnumBool" value="magnum" class='.$enabled_printer.'>';
} else {
echo '<input type="submit" name="submitMagnum" id="magnumBool" value="magnum" class='.$disabled_printer.'>';
}
}
else{
echo '<button id="magnum" class='.$lost_connection_printer.'>1. Magnum</button>';
}
echo '</div>
</form>';
P.s. note the use of "magnumBool" as a key isset instead of as a value: in this way (when possible) you will avoid duplicate entry and will make you code lighter if you have large arrays ;)
P.p.s. try always to keep you login separate from you template, this will make your code more readable and easier to maintain

Button Form POST Not Working

I have a simple button that hides once the event is triggered
<?php
//Define attributes
echo'<input type="submit" id="toggler" name="add_friend"class=button
value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</input>';
?>
//Hide the button
<script>
var hidden = false;
function action() {
if(!hidden) {
document.getElementById('toggler').style.visibility = 'hidden';
}
}
The above works as it should no problems , However when I add form to get method=POST for the button does not hide nor does my POST make it to $_POST['add_friend']
echo ' <form method="post" >
<input type="submit" id=toggler name="add_friend" class="button"
value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</input>
</form>';
How can I make correct this so that the button hides and my POST is passed on to my isset code please .
if (isset ($_POST['add_friend'])){
//rest of my code once the button is clicked and hidden
Thanks in advance .
Your JS is most likely hiding the element. Then your form gets submitted (the POST), only for the page to refresh and the button reappear.
It seems to me that you want to hijack form submission and process the request with ajax.
The following example code shows a similar problem with the Php form processing. You could adapt to your liking (I have left out the required Javascript):
<?php
$feedback = null;
$people = array(
1 => 'Samuel',
2 => 'Fred',
3 => 'Roger',
4 => 'Mavis'
);
$friends = array(3); // i.e. Roger
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$add_friend = isset($_POST['add_friend']) ? $_POST['add_friend'] : null;
if(array_key_exists($add_friend, $people) && !in_array($add_friend, $friends)) {
array_push($friends, $add_friend); // You probably want to save state here
$feedback = 'Added ' . $people[$add_friend] . ' as friend.';
}
}
?>
<?php echo isset($feedback) ? $feedback : ''; ?>
<form method="post">
<?php foreach ($people as $key => $person) { ?>
<button name=
"add_friend" onClick=
"action();" value=
"<?php echo $key ?>"
<?php echo in_array($key, $friends) ? 'disabled' : '' ?>
>
Friend <?php echo $person ?>
</button>
<?php } ?>
</form>
Checkboxes may be a better fit than buttons here.
A couple things wrong with this. You have an extra double quote before 'method' in your form, and should also add action="#" to the <form> tag. This tells the browser to send the result of the form to the current page. It's also good practise to add a hidden field to send your data, rather than adding it to the submit button. Try this and see if it works.
if (isset($_POST['add_friend'])) {
var_dump($_POST['add_friend']);
}
echo '
<form method="post" action="#">
<input type="hidden" name="add_friend" value="'.$output1['username'].'">
<input type="submit" id="toggler" class="button" value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</form>
';
Bear in mind this will essentially reload the page, so if you want to make an asynchronous request (EG, send some request without loading the page again) you will need to look into a solution with AJAX.
unless you didn't supply more information or copy/paste everything, you seem to have extra quotations here:
echo ' <form "method="post" >
Wrapping the input in a form will natively submit the form as well as fire your javascript. If you want to use an ajax solution, tie into the submit event and prevent the default action. (using jquery here):
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
// serialize() will get the form data, which can be used in ajax call
console.log( $( this ).serialize() );
});

How to send POST request using html button

I want to send post request using html button. I know it is easily done by jQuery ajax, but i do not want to use jquery and ajax. How can i do it?
This my function
public function editProduct() {
if($_SERVER['REQUEST_METHOD'] === 'POST') {
echo 'You are authorized';
} else {
echo 'You are not authorized to access this page.';
}
}
This is my HTML button
<button type="submit" onclick="location.href = '<?=base_url().'company/admin/add_product/editProduct?>';">Send Post Request</button>
In your form tag, just write a method="post"
<form method="post">
...
<button type="submit" >
</form>
You have two ways to do this:
via form (best method):
<form action ="<?php echo base_url().'company/admin/add_product/editProduct'?>" method="post">
<input type="submit" value="Send Post Request">
</form>
via javascript (jquery: http://api.jquery.com/jquery.post/ )

Issue sending POST data from html button tag to PHP processing script

I'm having a rather irritating issue when trying to submit data from a html button tag via POST to a PHP processing script.
Here's my code...
(1) HTML form:
<form id="pub-form1" method="post">
<button type="submit" name="All" value="true">All Publishers</button>
<button type="submit" name="Current" value="true">Current Publishers</button>
<button type="submit" name="Users" value="true">User Priveleges</button>
</form>
(2) jQuery script to handle POST request:
$(document).ready(function () {
$('#pub-form1').submit(function (e) {
e.preventDefault();
$('#results').contents().remove();
var formData = $(this).serialize();
$("input").prop("disabled", true);
request = $.post('VRC_PublishersProcess.php', formData, resultsMessage);
request.fail(function() {
$('#results').append("<span id=\"reply\">Your search failed for an unknown reason. Please try again in a few minutes.</ span>");
$("input").prop("disabled", false); });
function resultsMessage(data) {
$('#results').append(data);
$("input").prop("disabled", false);
}
});
});
(3) PHP processing script:
//All Publishers
if(isset($_POST['All'])) {
if(!empty($_POST['All'])) {
$result = $members->selectAllMembers();
if($result === true) {
exit(); //Kill the process
}
else {
echo $result;
exit(); //Kill the process
}
}
else {
$error = "<span id=\"reply\">Not all fields were entered correctly!</ span>";
echo $error;
exit(); //Kill the process
}
}
//Current Publishers
if(isset($_POST['Current'])) {
if(!empty($_POST['Current'])) {
$result = $members->selectCurrentPublishers();
if($result === true) {
exit(); //Kill the process
}
else {
echo $result;
exit(); //Kill the process
}
}
else {
$error = "<span id=\"reply\">Not all fields were entered correctly!</ span>";
echo $error;
exit(); //Kill the process
}
}
//Users
if(isset($_POST['Users'])) {
if(!empty($_POST['Users'])) {
$result = $members->selectUserPublishers();
if($result === true) {
exit(); //Kill the process
}
else {
echo $result;
exit(); //Kill the process
}
}
else {
$error = "<span id=\"reply\">Not all fields were entered correctly!</ span>";
echo $error;
exit(); //Kill the process
}
}
I'm not quite sure what the cause of the issue is. No errors were thrown by javascript or PHP; the page remains blank with no results.
The jQuery function seems to be working correctly. I've use that particular several times on other forms and it handles the POST request properly. I was even able to trigger a failure on it; it responded correctly.
The PHP processing script also appears to be functioning properly. Again, it derived from other scripts that have successfully processed POST requests from the same page.
My suspicion is focused on the HTML form itself. These are my theories: (1) The button isn't submitting "itself." In other words, since there is no text or other forms of input, there's really nothing to submit. (2) For some reason the name is not corresponding to what my PHP script is looking for. For instance, if "All Publishers" was submitted, my PHP script is looking for $_POST['All']. But for some reason, that request isn't saved under that identifier in the PHP superglobal array.
My goal is to provide the end user with three options of displaying data. Right now, that isn't working.
Any feedback is appreciated.
Final Solution:
<div id="pub1">
Other
<div id="displayselect" method="post">
<form id="select1" method="post">
<input type="hidden" name="All" value="1" />
</form>
<form id="select2" method="post">
<input type="hidden" name="Current" value="1" />
</form>
<form id="select3" method="post">
<input type="hidden" name="Users" value="1" />
</form>
<button type="submit" name="All" form="select1">All Publishers</button>
<button type="submit" name="Current" form="select2">Current Publishers</button>
<button type="submit" name="Users" form="select3">User Priveleges</button>
</div>
</div>
Obviously, appropriate modifications were made in the jQuery...
Figured it out,
jQuery.serialize didn't work out on the button (http://api.jquery.com/serialize/) it only works on input, textarea, select so I tried switching your HTML button elements into <input type="submit" ... but that didn't work out as well because jQuery ignores the submit tags when serializing, I tried to add an <input type="hidden" name="test" value="1" /> and checked out what it serialized was test=1 so you'd have to change your form a bit.
jsFiddle for testing: http://jsfiddle.net/4D8Nz/

HTML Submit Button Branching

On a series of web forms users needs to be able to move forwards and backwards. However I want to process the form irrespective of which direction they are going.
The buttonshave name of "submit" and values of "back" and next". How do I interpret the value?
This doesn't work :-)
if(isset($_POST[$submit['back']])) { header('location: ../pages/create_page1.php'); }
if(isset($_POST[$submit['next']])) { header('location: ../pages/create_page3.php'); }
The the name of the field is called submit, so you need to check if the field has been submitted and what its value is:
if ( isset($_POST['submit]') && $_POST[submit] == 'back' )
However you aren't using submit buttons, you are using server side image maps, so the value might not have been submitted (depending on the browser).
Instead you need to give the fields different names, and then check to see if co-ordinates were sent for those fields.
<input type="image" name="submit_back" src="../images/arrows/back_50.png" width="121" height="50" border="0" alt="Back" />
if ( isset($_POST['submit_back_x']) )
Try to use jquery:
$('#some_button').click(funnction(){
var $Data = $('#some-data-input').val();
if($Data.length > 0){ // or some else
window.location.href = "../pages/create_page3.php";
} else {
// other action
}
});
Try this javascript function...
<script language=javascript>
function redirect()
{
if(document.value=="Next")
{
document.form.action="next.php";
}
else if(document.value=="Back")
{
document.form.action="back.php";
}
return true;
}
</script>
<form method="post" name=form onsubmit='return redirect();'>
<p>Click...</p>
<input type="submit" name="back" value="Back"/>
<input type="submit" name="next" value="Next"/>
</form>
You can't get the button value with $submit, it should be $_POST['submit'].
You can try this script.
<?php
if(isset($_POST['next'])) {
$submit = 'Next button was clicked.';
// header(...);
} elseif(isset($_POST['back'])) {
$submit = 'Back button was clicked.';
// header(...);
} else {
$submit = '';
}
?>
<form action="" method="post">
<p>Click...</p>
<input type="submit" name="back" value="Back"/>
<input type="submit" name="next" value="Next"/>
</form>
<br/><?=$submit;?>
Or with same button name and arrows like on your comments:
<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'next') {
$submit = 'Next button was clicked.';
// header(...);
} elseif(isset($_POST['submit']) && $_POST['submit'] == 'back') {
$submit = 'Back button was clicked.';
// header(...);
} else {
$submit = '';
}
?>
<form action="" method="post">
<p>Click...</p>
<input type="image" name="submit" src="http://cdn4.iconfinder.com/data/icons/brightmix/128/monotone_arrow_left_small.png" value="back"/>
<input type="image" name="submit" src="http://cdn4.iconfinder.com/data/icons/brightmix/128/monotone_arrow_right.png" value="next"/>
</form>
<br/><?=$submit;?>

Categories