one form multiply tasks with php - php

I am making an CMS, and the pages that are going to be made by the clients, they are going to use the same form to edit the page, add new page, add new subpage, edit the subpage.. I dont want to copy that form multiply times for each action. I would like to know if anyone of you has an idea how to use that form for all of the actions in the best way.
<div class="containerholder">
<div class="container">
<div id="contain">
<form method="post" id="customForm" action="edited.php">
<div>
<label for="name">Navigation</label>
<input id="name" name="navigation" type="text" value="<?php echo $navigation ?>" />
</div>
<div>
<label for="message">Content</label>
<textarea id="content" name="content" cols="" rows="" ><?php echo $content ?></textarea>
</div>
<div>
<input type="hidden" name="id" id="id" value="<?php echo $id ?>">
<input id="send" name="send" type="submit" value="Save and update" />
</div>
</form>
</div>
</div></div>
this is the form if you want to see it, I have an idea how to make it but it doesnt look to me like it is the best way (professional).
Thank you for your time!

Use multiple submit-buttons for every task and identify the requested task by the name of the submit-button(usually only a clicked submit-button is submitted)
Professional: it's not "professional" in my eyes to use a single form for all tasks.

You could use multiple submit buttons, as google does with its search/feeling lucky choice:
<input id="send" name="send" type="submit" value="edit" />
<input id="send" name="send" type="submit" value="new page" />
<input id="send" name="send" type="submit" value="edit subpage" />
<input id="send" name="send" type="submit" value="new subpage" />
The name=value pair for the submit button is transmitted as it is for the rest of the form data, so at the server it is collected using the same functionality ($_GET or $_POST etc.)
Alternatively, you could use form controls and javascript events to control the communication to the server via AJAX (it's more flexible, you can control exactly what data is transmitted via javascript, and it's seamless for the end-user who isn't waiting for page reloads). See http://www.w3schools.com/ajax for simple source code.

add two or more radio button to select you function, for example :
<form action="" method="post">
...
<input type="radio" name="function" value="Add" />
<input type="radio" name="function" value="Delete" />
<input type="radio" name="function" value="Edit" />
..
</form>
and in php :
<?PHP
...
if( $_POST['function'] == 'Add' )
{
//Add Function
} else
if( $_POST['function'] == 'Delete' )
{
//DeleteFunction
} else
if( $_POST['function'] == 'Edit' )
{
//EditFunction
}
...
?>

I would suggest making a single form, and then using scripting to switch it between modes and datafill the fields as required.
For links directing to the form.
/* To create a New Record */
New Record
/* To delete an Existing Record */
Delete #123
/* To edit an Existing Record */
Delete #123
For the form file (in my example thisfile.php itself).
<?php
if( isset( $_GET['action'] ) ){
switch( strtolower( $_GET['action'] ) ){
case 'delete' :
/* Perform Deletion Action Here */
break;
case 'edit' :
if( isset( $_POST['save'] ) ){
/* Perform Modification of Existing Values Here */
}else{
/* Perform Query for Existing Values Here */
}
break;
case 'new' :
if( isset( $_POST['save'] ) ){
/* Perform Creation of New Record Here */
}else{
/* Set Default Values */
$navigation = '';
$content = '';
}
break;
}
}
?>
<div class="containerholder">
<div class="container">
<div id="contain">
<form method="post" id="customForm">
<?php if( isset( $_GET['action'] ) ){ ?>
<input type="hidden" name="action" value="<?php echo $_GET['action']; ?>" />
<?php } ?>
<?php if( isset( $_GET['record'] ) ){ ?>
<input type="hidden" name="record" value="<?php echo $_GET['record']; ?>" />
<?php } ?>
<div>
<label for="name">Navigation</label>
<input id="name" name="navigation" type="text" value="<?php echo $navigation ?>" />
</div>
<div>
<label for="message">Content</label>
<textarea id="content" name="content" cols="" rows="" ><?php echo $content ?></textarea>
</div>
<div>
<input id="send" name="send" type="submit" value="Save and update" />
</div>
</form>
</div>
</div>
</div>

Related

$_POST["action"] == "edit"

How can I go to this if (isset($_POST["action"]) && $_POST["action"] == "edit") statement?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["action"]) && $_POST["action"] == "edit") {
//Assemble the the postData
);
//Call the RestClient with PUT
RestClient::call("PUT",$postData);
}
}
When I click the 'edit' button like this?
<h4>Edit Customer - <?php echo $c->getCustomerID(); ?></h4>
<!-- The above form looks like this -->
<form method="POST" ACTION="<?php echo $_SERVER["PHP_SELF"]; ?>">
<!-- Would some hidden fields help to route the data? Probably -->
<div class="row">
<div class="six columns">
<label for="name">name</label>
<input type="text" name="ename" value=<?php echo $c->getName();?>>
</div>
<div class="six columns">
<label for="name">address</label>
<input type="text" name="eaddress" value=<?php echo $c->getAddress();?>>
</div>
<div class="six columns">
<label for="name">City</label>
<input type="text" name="ecity" value=<?php echo $c->getCity();?>>
</div>
</div>
<input class="button-primary" type="submit" value="Edit">
</form>
If you meant to catch your submit button's value, the first thing you have to do is give it a name with the value of "action":
<input class="button-primary" name="action" type="submit" value="Edit">
And then match your button's value exactly (meaning case-sensitive):
if (isset($_POST["action"]) && $_POST["action"] === "Edit")
That's how you would do it, although it doesn't make sense unless you're going to have multiple forms where each submit button's name is "action", and doing so is not a good practice. A much more sensible approach is just giving the submit a name that reflects the action:
<input class="button-primary" name="edit" type="submit" value="Edit">
And then simply check if that name is set:
if (isset($_POST["edit"]))
Also note that ACTION="<?php echo $_SERVER["PHP_SELF"]; ?>" is unnecessary, as the default action is to submit to self, so you can just drop the entire attribute.
You just need to add a hidden input
<input type="hidden" name="action" value="edit"/>

How to get two html forms working in one .php file?

Now i have 4 buttons on my page. They define different parameters. What i want to do, is use php switch case, and after pressing for example button1 i want the datetimepicker, and a chart appear as well. I read that i can manage with that problem using two html forms in one php file adding form id, but im only getting the first form to work properly while the second one seems to fail with sending the data using POST method. Below how i try to do this:
<form id="switch" action="data-from-database.php" method="post">
<h2 align="center">Wybierz interesujący Cię przedział
czasowy</h2></br>
<div id="pudlo">
<input type="submit" name="przycisk"
class="input_wykresy" value="temperatura" form="switch">
<input type="submit" name="przycisk"
class="input_wykresy" value="wilgotność" form="switch">
<input type="submit" name="przycisk"
class="input_wykresy" value="ciśnienie" form="switch">
<input type="submit" name="przycisk"
class="input_wykresy" value="irradiancja" form="switch">
</div>
</form>
<?php
//PHP part here is what i want to appear on the page after using switch
switch ($_REQUEST['przycisk'])
{
case "temperatura":
//Once again HTML part
?>
<form id="picker" action="data-from-database.php" method="post">
<input type="text" name="from_date"
id="from_date" class="input_wykresy1" placeholder="Od" autocomplete="off">
<input type="text" name="to_date" id="to_date"
class="input_wykresy1" placeholder="Do" autocomplete="off">
<input type="submit" name="filter" id="filter" value="Wyszukaj"
form="picker" class="input_wykresy"/>
</form>
<?php
if (isset($_POST["from_date"], $_POST["to_date"])) // php code which i want to work in case
{
$handle = $link->prepare("SELECT temperatura, czaspomiaru FROM Pomiary
WHERE czaspomiaru BETWEEN'" . $_POST["from_date"] . "' AND
'" . $_POST["to_date"] . "'");
}
$dataPoints = [];
//Best practice is to create a separate file for handling connection to database
try
{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
if ($result)
{
foreach ($result as $row)
{
array_push($dataPoints, ["label" => $row->czaspomiaru, "y" =>
$row->temperatura]);
}
}
else
{
?>
<div>
<h2>
<center>Nie znaleziono pasujących rezultatów</center>
<h2>
</div>
<?php
}
$link = null;
}
catch (\PDOException $ex)
{
print($ex->getMessage());
}
}
First form working properly, which i tested on buttons. Second one doesnt work, because when i press the submit button refering to datetimepickers, nothing shows on chart i assume no data been sent. I wonder how can i get the second form working?
You might want a hidden field holding the name/value pair of the button taking you to the subform since the button is not part of that form.
<form id="picker" action="data-from-database.php" method="post">
<input type="hidden" name="przycisk" value="temperatura">
<input type="text" name="from_date"
id="from_date" class="input_wykresy1" placeholder="Od" autocomplete="off">
<input type="text" name="to_date" id="to_date"
class="input_wykresy1" placeholder="Do" autocomplete="off">
<input type="submit" name="filter" id="filter" value="Wyszukaj"
form="picker" class="input_wykresy"/>
</form>
Or, since you do not use the submit button name="filter" in your PHP code, you could just alter that button.
<form id="picker" action="data-from-database.php" method="post">
<input type="text" name="from_date"
id="from_date" class="input_wykresy1" placeholder="Od" autocomplete="off">
<input type="text" name="to_date" id="to_date"
class="input_wykresy1" placeholder="Do" autocomplete="off">
<input type="submit" id="filter" name="przycisk" value="temperatura"
form="picker" class="input_wykresy"/>
</form>
Consider using four radio buttons (instead of four submit buttons). Your site visitor(s) can select which radio button and submit. The code could easily be handled with if, elseif, else conditions, and the output could appear in one designated area, regardless of which radio button was selected.
<form id="switch" action="data-from-database.php" method="post">
<h2 align="center">Wybierz interesujacy Cie przedzial
czasowy</h2></br>
<div id="pudlo">
<input type="radio" name="przycisk" class="input_wykresy" value="temperatura">
<input type="radio" name="przycisk" class="input_wykresy" value="wilgotnosc" >
<input type="radio" name="przycisk" class="input_wykresy" value="cisnienie" >
<input type="radio" name="przycisk" class="input_wykresy" value="irradiancja" >
<input type="submit" value="submit">
</div>
</form>
<?php
if (przycisk === "temperatura") {
echo "yada";
} elseif (przycisk === "wilgotnosc") {
echo "yada";
} elseif (przycisk === "cisnienie") {
echo "yada";
} else {
echo "yada";
}
?>

Button getting hided if validation fails --php css wordpress

field validation is from php(server side).
upload button is client side(ext and file size).
for both field only one save button.
My goal is to hide save button once submitted and show processing...
but if validation fails save button will be hided.
<form id="form" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<?php /* NOTICE: here we storing id to determine will be item added or updated */ ?>
<input type="hidden" name="id" value="<?php echo $item['id'] ?>"/>
<div class="metabox-holder" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<?php /* And here we call our custom meta box */ ?>
<?php do_meta_boxes('person', 'normal', $item); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="<?php _e('Save', 'custom_table_example')?>" id="submit" class="button-primary" name="submit" onclick="$('#submit').hide(); $('#submit1').show();" / >
<input type="submit1" name="submit1" id="submit1" class="button-primary" value="PROCESSING...." style="display:none; >
</div>
</div>
</div>
</form>
jquery code
jQuery(document).ready(function($){
console.log("plugin script loaded1");
$('#submit').click( function() {
$("#submit").hide();
$("#submit1").show();
});
});

PHP - Consecutive submits on same page

Can I make consecutive submits and stay on the same page?
I need one form to fill, and then second, and then third, and so on... and have to trigger different functions and forms based on the answer.For example:
<form method="post">
Sex?<input type="text" name="sex">
<input type="submit" name ="submit_sex" value="Submit">
</form>
<?php
if(isset($_POST['submit_sex'])){
echo("Fist submit done");
?>
<form method="post">
Age?<input type="text" name="age">
<input type="submit" name ="submit_age" value="Submit">
</form>
<?php
if(isset($_POST['submit_age'])){
echo("Second submit done");
}
}
?>
Yes you can, however it would look prettier/be more user-friendly if done with Ajax. In your case though, it'll be more efficient to use conditional statements to detect which form to display, and for the sake of absolute minimum input validation, you should at least check for empty values:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if(isset($_POST['third_question']) && $_POST['third_question'] != "") {
// store value of $_POST['third_question'] in a cookie
// Last question answered, do what you need to next with all the values
} elseif(isset($_POST['second_question']) && $_POST['second_question'] != "") {
// store value of $_POST['second_question'] in a cookie
Third Question? <input type='text' name='third_question' />
} elseif(isset($_POST['first_question']) && $_POST['first_question'] != "") {
// store value of $_POST['first_question'] in a cookie, then display next quesion
Second Question? <input type='text' name='second_question' />
} else {
First Question? <input type='text' name='first_question' />
}
?>
<input type="submit" name="submit" value="Submit" />
</form>
I think it would make more sense to just do this on the browser side. You could do something like:
<form method="post">
<div id="sexInput">
Sex?<input type="text" name="sex" />
<input type="button" name="submit_sex" value="Submit" onClick="showAge()" />
</div>
<div id="ageInput" style="display:none;">
Age?<input type="text" name="age" />
<input type="submit" value="Submit" />
</div>
</form>
and have a function showAge() that hides the sexInput div and displays the ageInput div. This way it is really all one form, that gets submitted all at once at the end, but it is displayed to your user one part at a time.

How to access the form's 'name' variable from PHP

I'm trying to create a BMI calculator. This should allow people to use either metric or imperial measurements.
I realise that I could use hidden tags to solve my problem, but this has bugged me before so I thought I'd ask: I can use $_POST['variableName'] to find the submitted variableName field-value; but...I don't know, or see, how to verify which form was used to submit the variables.
My code's below (though I'm not sure it's strictly relevant to the question):
<?php
$bmiSubmitted = $_POST['bmiSubmitted'];
if (isset($bmiSubmitted)) {
$height = $_POST['height'];
$weight = $_POST['weight'];
$bmi = floor($weight/($height*$height));
?>
<ul id="bmi">
<li>Weight (in kilograms) is: <span><?php echo "$weight"; ?></span></li>
<li>Height (in metres) is: <span><?php echo "$height"; ?></span></li>
<li>Body mass index (BMI) is: <span><?php echo "$bmi"; ?></span></li>
</ul>
<?php
}
else {
?>
<div id="formSelector">
<ul>
<li>Metric</li>
<li>Imperial</li>
</ul>
<form name="met" id="metric" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">
<fieldset>
<label for="weight">Weight (<abbr title="Kilograms">kg</abbr>):</label>
<input type="text" name="weight" id="weight" />
<label for="height">Height (<abbr title="metres">m</abbr>):</label>
<input type="text" name="height" id="height" />
<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
</fieldset>
<fieldset>
<input type="reset" id="reset" value="Clear" />
<input type="submit" id="submit" value="Submit" />
</fieldset>
</form>
<form name="imp" id="imperial" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">
<fieldset>
<label for="weight">Weight (<abbr title="Pounds">lbs</abbr>):</label>
<input type="text" name="weight" id="weight" />
<label for="height">Height (Inches):</label>
<input type="text" name="height" id="height" /
<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
</fieldset>
<fieldset>
<input type="reset" id="reset" value="Clear" />
<input type="submit" id="submit" value="Submit" />
</fieldset>
</form>
<?php
}
?>
I verified that it worked (though without validation at the moment -I didn't want to crowd my question too much) with metric; I've added the form but not the processing for the imperial yet.
To identify the submitted form, you can use:
A hidden input field.
The name or value of the submit button.
The name of the form is not sent to the server as part of the POST data.
You can use code as follows:
<form name="myform" method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="frmname" value=""/>
</form>
You can do it like this:
<input type="text" name="myform[login]">
<input type="password" name="myform[password]">
Check the posted values
if (isset($_POST['myform'])) {
$values = $_POST['myform'];
// $login = $values['login'];
// ...
}
The form name is not submitted. You should just add a hidden field to each form and call it a day.
In the form submitting button (id method of form is post):
<input type="submit" value="save" name="commentData">
In the PHP file:
if (isset($_POST['commentData'])){
// Code
}
For some reason, the name of the submit button is not passed to the superglobal $_POST when submitted with Ajax/jQuery.
Use a unique value on the submit button for each form like so
File index.html
<form method="post" action="bat/email.php">
<input type="text" name="firstName" placeholder="First name" required>
<input type="text" name="lastName" placeholder="Last name" required>
<button name="submit" type="submit" value="contact">Send Message</button>
</form>
<form method="post" action="bat/email.php">
<input type="text" name="firstName" placeholder="First name" required>
<input type="text" name="lastName" placeholder="Last name" required>
<button name="submit" type="submit" value="support">Send Message</button>
</form>
File email.php
<?php
if (isset($_POST["submit"])) {
switch ($_POST["submit"]) {
case "contact":
break;
case "support":
break;
default:
break;
}
}
?>
As petervandijck.com pointed out, this code may be susceptible to XSS attacks if you have it behind some kind of log-in system or have it embedded in other code.
To prevent an XSS attack, where you have written:
<?php echo "$weight"; ?>
You should write instead:
<?php echo htmlentities($weight); ?>
Which could even be better written as:
<?=htmlentities($weight); ?>
You can use GET in the form's action parameter, which I use whenever I make a login/register combined page.
For example: action="loginregister.php?whichform=loginform"
I had a similar problem which brought me to this question. I reviewed all the preceding answers, but ultimately I ending up figuring out my own solution:
<form name="ctc_form" id="ctc_form" action='' method='get'>
<input type="hidden" name="form_nm" id="form_nm">
<button type="submit" name="submit" id="submit" onclick="document.getElementById('form_nm').value=this.closest('form').name;">Submit</button>
</form>
It seamlessly and efficiently accomplishes the following:
Passes the form name attribute via a hidden input field, without using the fallible value attribute of the submit button.
Works with both GET and POST methods.
Requires no additional, independent JavaScript.
You could just give a name to the submit button and do what needs to be done based on that. I have several forms on a page and do just that. Pass the button name and then if button name = button name do something.
Only the names of the form fields are submitted, but the name of the form itself is not. But you can set a hidden field with the name in it.

Categories