Solved

How to have a form post to one page or another depending on what button was pressed

Posted on 2016-11-24
15
30 Views
Last Modified: 2016-11-25
I have a form that contains a text field, an update button and a delete button. if they user pressed update it must post to update.php for example and if they press delete it must post to delete.php

I am trying to do this in order to avoid using GET and showing the record id's in the URL.

$showLocation = <<<EOD
		<form method="post" action="">
		<tr>
		<td> <input type="category" name="locationName" value="$locationName"></td>
		<td></td>
		<td></td>
		<td></td>
		<td><input type="submit" name="locEdit" class="btn btn-xs btn-fill btn-warning "value="Edit"><input type="hidden" name="locationId" value="$locationId"></td>
		<td><input type="submit" name="locDelete" class="btn btn-xs btn-fill btn-danger "value="Delete"><input type="hidden" name="locationId" value="$locationId"></td>
		</tr>
		</form>
		
EOD;
echo $showLocation;

Open in new window


I'm not sure if I can use an if statement with a form or not or should I make it post to itself. What would be the best way to do this?
0
Comment
Question by:Black Sulfur
15 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41900821
That is not good design. Each form should have one end point and in that endpoint you route the request based on the parameters in the request.

Usually the delete is separate from the update form - it is usually associated with the list of records (grid view). However, you can included it on the form. The sample below demonstrates the concept only - you should adapt it to meet your particular requirements.
HTML
<form action="formhandler.php" method="post">
  Name: <input type="text" value="Fred Smeggles" name="fullname" />
  <button class="btn btn-primary" type="submit" name="action" value="update">Update</button>
  <button class="btn btn-danger" type="submit" name="action" value="delete">Delete</button>
</form>

Open in new window

PHP (formhandler.php)
<?php

$action = isset($_POST['action']) ? $_POST['action'] : 'default';

// You can either do an if / else on the action here
// if ($action == 'update') {
//    Handle update here
// }
// else {
//    Handle delete here
// }

// OR we can be a bit more risque and go for the dynamic include
// make a filename but make sure we salt it so that an enterprising
// user does not decide to try and get our script to run code we
// don't want him/her to

// Essentially what we are doing is using our action variable to link to
// a file that handles that action. To extend our action set all we need 
// to do is add a file with the prefix act__ followed by the action we 
// want to handle and the script does the rest.
$path = "actions/act__{$action}.php";

// We can do a redirect here or a require
// The effect will be the same
if (file_exists($path)) {
  require_once($path);
}

die();

Open in new window

Update Script (actions/act__update.php)
<?php
$fullname = isset($_POST['fullname']) ? $_POST['fullname'] : 'No name specified';
echo "You selected to <b>UPDATE</b> {$fullname}";
?>
<div>Click <a href="t1897.html">here</a> to return to main page</div>

Open in new window

Delete script (actions/act__delete.php)
<?php
$fullname = isset($_POST['fullname']) ? $_POST['fullname'] : 'No name specified';
echo "You selected to <b>DELETE</b> {$fullname}";
?>
<div>Click <a href="t1897.html">here</a> to return to main page</div>

Open in new window

Default (actions/act__default.php) - because you never know
<?php
echo "You did not select a valid action";

Open in new window

Working sample here
0
 

Author Comment

by:Black Sulfur
ID: 41900825
Okay, so would this be a bad idea?

	$postform = htmlspecialchars($_SERVER["PHP_SELF"]);
			$showLocation = <<<EOD
		<form method="post" action="$postform">
		<tr>
		<td> <input type="category" name="locationName" value="$locationName"></td>
		<td></td>
		<td></td>
		<td></td>
		<td><input type="submit" name="locEdit" class="btn btn-xs btn-fill btn-warning "value="Edit"><input type="hidden" name="locationId" value="$locationId"></td>
		<td><input type="submit" name="locDelete" class="btn btn-xs btn-fill btn-danger "value="Delete"><input type="hidden" name="locationId" value="$locationId"></td>
		</tr>
		</form>
		
EOD;
echo $showLocation;

Open in new window



if(isset($_POST['locEdit'])) {
		
		$stmt = $link->prepare("UPDATE `location` SET `location_name` = ? WHERE `location_id` = ? LIMIT 1");
		$stmt->bind_param("si", $_POST['locationName'], $_POST['locationId']);
		$stmt->execute();
		$stmt->close();

Open in new window

0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 25 total points
ID: 41900840
I agree with Julian.  Feed the data to a single 'action' page and let it sort out what is needed.  You can use a 'header' statement if you need to end up on a different page.  

And "value="Edit"  is not valid.  You need a space before the 'value' attribute.

And in $postform = htmlspecialchars($_SERVER["PHP_SELF"]);, the 'htmlspecialchars' is unnecessary.

And <tr> without a table enclosing it is also not valid.  And if you have a <table> that is not shown, putting a <form> around a <tr> is also not valid though the browser may make it work anyway.  Anything you put between <tr> statements will be relocated by the browser to a position before the table so you may not get what you wanted.
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 400 total points
ID: 41900845
You can - I prefer to give me action inputs the name action - you cannot press the delete and edit button at the same time - so only one action is valid. This way you check for one incoming - action - and then route on that.

So in your example
<td><input type="submit" name="action" class="btn btn-xs btn-fill btn-warning "value="Edit"><input type="hidden" name="locationId" value="$locationId"></td>
<td><input type="submit" name="action" class="btn btn-xs btn-fill btn-danger "value="Delete"><input type="hidden" name="locationId" value="$locationId"></td>

Open in new window


$action = isset($_POST['action']) ? $_POST['action'] : false;
if ($action == 'update') {
}
else if ($action == 'delete') {
}

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41900859
Thanks for the feedback guys. Just to clear things up a bit Dave, I now need to put the table into the heredoc. I had it outside because I was originally trying to do this with ajax but once again it defeated me and I decided to just use php. So, I had the table like this:

<tbody id="addToTable">
<?php display_locations($link); ?>
</tbody>

Open in new window


the display_locations function then had the table <tr> and <td> using heredoc as you can see from my original post. Since I won't be using ajax at this stage and therefore don't need the tbody id, I can scrap that idea and include the tbody in the heredoc.

Regarding the 'htmlspecialchars', I just used that as it was on the W3schools website in the contact form example where the form posts to itself.

Regarding "value="Edit", that was a mistake on my part as the " was actually the closing of the class, I just need to backspace it by one.

class="btn btn-xs btn-fill btn-warning "value="Edit"

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41900861
Right, it sounds like I should rather do what you guys suggest. I will give that a go and will let you know how I get on. Thanks for the input thus far! :)
0
 

Author Comment

by:Black Sulfur
ID: 41900863
Oh, just one thing though. will I still be able to use the sweet alert using your methods? I had it working quite nicely with the form posting to itself like this:

function delete_location($link){
	
	if(isset($_POST['locDelete'])) {
		
		$stmt = $link->prepare("DELETE FROM `location` WHERE `location_id` = ? LIMIT 1");
		$stmt->bind_param("i", $_POST['locationId']);
		$stmt->execute();
		$stmt->close();
		echo $sa = "<script type=\"text/javascript\"> 
	swal({
	title: \"Deleting record..\",
	text: \"Please be patient.\",
	type: 'error',
	timer: 4000,
	showConfirmButton: false });
	
	 setTimeout(function(){
	 window.location.href = 'locations.php'; 
	 }, 3000);
	
    </script>";
	}
}

Open in new window

0
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41900868
I would put the Sweet Alert in the <script> section of the page that has the form with the Delete button and bind the click on the Delete button to load the sweet alert.

Post back if you want a sample.
0
 

Author Comment

by:Black Sulfur
ID: 41900872
yeah, please provide me with an example! I used your code and added the edit and delete records and it works 100%. No sweet alert obviously..

$action = isset($_POST['action']) ? $_POST['action'] : false;
if ($action == 'Edit') {
	
	$stmt = $link->prepare("UPDATE `location` SET `location_name` = ? WHERE `location_id` = ? LIMIT 1");
		$stmt->bind_param("si", $_POST['locationName'], $_POST['locationId']);
		$stmt->execute();
		$stmt->close();
	header("location:locations.php");
	
}

else if ($action == 'Delete') {
	
		$stmt = $link->prepare("DELETE FROM `location` WHERE `location_id` = ? LIMIT 1");
		$stmt->bind_param("i", $_POST['locationId']);
		$stmt->execute();
		$stmt->close();
	header("location:locations.php");
}

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41900889
Just had another look - that Sweet Alert is geared more to an AJAX request. You are doing the delete and after it is done showing the "Please wait message ..." - basically making the user wait for nothing.

What is the benefit of the message over an onscreen message that says "Record successfully deleted"

You could have a fade out of the message if you want

<div class="fade-out alert alert-success">Record successfully deleted</div>
<script>
setTimeout(function() {
  $('.fade-out').fadeOut(2000, function() {
      $(this).remove();
  });
}, 3000);
</script>

Open in new window

Working sample here
0
 

Author Comment

by:Black Sulfur
ID: 41901162
Haha, true. They are being made to wait for nothing. But, I just really like the sweet alert message more than any other type of message because you can't miss it. Sometimes a message that shows at the top of the screen like a bootstrap alert or something gets overlooked if there is a lot of stuff going on. I thought with the sweet alert it fades the rest of the page out and you get a nice big alert in the middle of the page which is why I really like it.

So, are you saying I cannot make use of the sweet alert unless I use ajax? I had it working when I was posting the form to itself but obviously that was different to how I have it working now since I changed it to your and Dave's suggestion and I can't use it like that anymore.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41901182
No I said that it was more suited to an AJAX call. Nothing stopping you using it but personally I would find it annoying after a while.

Remember you need to evaluate a system like this - which is an operational application not a marketing one - from the perspective of how the user will see it on the 100th time. Too often developers go for "cool" which is fine the first or second time but becomes annoying later on.
1
 

Author Comment

by:Black Sulfur
ID: 41901620
Haha, good points. The novelty would wear off pretty quick I suppose. Okay, but whether I use it or your example, how do I get it to run only when I click on edit or delete or better yet, when the php has actually been executed successfully and the record was updated or deleted. Now, that message just displays on page load.
0
 

Author Comment

by:Black Sulfur
ID: 41901648
So, I had an idea to do this and it seems to work. I just want to know if it is an acceptable way or not. It seems long winded but I really can't think of a better way due to inexperience. The thinking is that on the formhandler.php I set a session variable. Then when the edit or delete has run and it redirects back to the page displaying the records, I do a check there to see if that session variable exists. If it does, the message is displayed and the session is unset so that if you refresh the page or come back, the message doesn't pop up again until you perform another edit or delete.

For the purpose of this example I have used the sweet alert but I will probably change it because Julian is right, it is pretty annoying after a while because you have to wait for it to go away before you can carry on doing anything. Please let me know if there is a better way to do this as I was just guessing here.

formhandler.php

$_SESSION['refer'] = "SA";

$action = isset($_POST['action']) ? $_POST['action'] : false;
if ($action == 'Edit') {
	
	$stmt = $link->prepare("UPDATE `location` SET `location_name` = ? WHERE `location_id` = ? LIMIT 1");
		$stmt->bind_param("si", $_POST['locationName'], $_POST['locationId']);
		$stmt->execute();
		$stmt->close();
	header("location:locations.php");
	
}

else if ($action == 'Delete') {
	
		$stmt = $link->prepare("DELETE FROM `location` WHERE `location_id` = ? LIMIT 1");
		$stmt->bind_param("i", $_POST['locationId']);
		$stmt->execute();
		$stmt->close();
	header("location:locations.php");
}

Open in new window


Original page displaying table of records:

 
  if(isset($_SESSION['refer'])) {
    
    echo $sa = "<script type=\"text/javascript\"> 
    swal({
    title: \"Record updated!\",
    text: \"blah blah blah.\",
    type: 'success',
    timer: 2000,
    showConfirmButton: false });
    </script>";
            
    unset($_SESSION['refer']);
    
} else {
    
    false;
}

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 75 total points
ID: 41901668
From line 14 to end of the last code snippet.  This is not needed.  The else clause would only be needed if it had to actually do something.
else {
    
    false;
}

Open in new window

From the top of that snippet.  This would be a really good place to use a HEREDOC declaration.  Also, I'm not sure what echo would do with an assignment statement.  
    echo $sa = "<script type=\"text/javascript\"> 
    swal({
    title: \"Record updated!\",
    text: \"blah blah blah.\",
    type: 'success',
    timer: 2000,
    showConfirmButton: false });
    </script>";

Open in new window


For clarity, I might write it more like this:
    $sa = <<<EOS
    <script type="text/javascript"> 
    swal({
    title: "Record updated!",
    text: "blah blah blah.",
    type: 'success',
    timer: 2000,
    showConfirmButton: false });
    </script>
EOS;
    echo $sa;

Open in new window

1

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now