Form data and Button in the same _POST - php

Evening!
I'm having a spot of an issue figuring out how to get a particular section of code to work, I have this:
<form>
TestCheckBox
<input type="checkbox" name="TestCheckBox" value="Yes" />
</form>
<div id="search">
<input type="text" id="search_bar" />
<input type="button" value="Search!" />
</div>
And in a php file, I have this:
if($_POST['TestCheckBox'] == 'Yes'){
echo "TEST";
}
if (isset($_POST['action']) && !empty($_POST['action'])) {
generateHTML($_POST['action']);
}
else {
echo "NOTHING IS HERE";
}
Obviously this is not how to do this. I'm curious as to hwo I can make my search bar submit the post data also included in the checkbox.
(It's for a search bar, and the checkboxes are advanced search options, so naturally I only want one search button).
Thank you!

Give the inputs names (without them they cannot be successful controls)
Put them inside the form (otherwise they are only useful to client side scripts)
Make the form make a POST request (it defaults to GET).
Use a submit button so the form will be submitted (regular buttons are only for client side scripts)
It is also beneficial to include labels (which inform users what controls are for and provide larger click targets (the latter is especially important for checkboxes and radio buttons)).
Such:
<form method="post">
<label for="TestCheckBox">TestCheckBox</label>
<input type="checkbox" name="TestCheckBox" id="TestCheckBox" value="Yes" />
<div id="search">
<label for="search_bar">Query</label>
<input type="text" id="search_bar" name='action' />
<input type="submit" value="Search!" />
</div>
</form>

You have to wrap the <form> around all the <inputs>.
<form>
TestCheckBox
<input type="checkbox" name="TestCheckBox" value="Yes" />
<div id="search">
<input type="text" id="search_bar" />
<input type="button" value="Search!" />
</div>
</form>

Related

Submit form in two different ways

I have a form with two "a" links. Both should submit form, but in two different ways.
This is html I currently have.
HTML:
<form method="post" id="doc_form" target="somwhere">
<textarea name="doc_text"><?php echo $file; ?></textarea>
<input type="hidden" name="submitted" value="1" />
</form>
<a id="doc_send_email" class="btn">SEND</a>
<a id="pritn_pdf_btn" onclick="document.getElementById('doc_form').submit();" class="btn">Print <span class="span_pdf">PDF </span></a>
When user clicks on #pritn_pdf_btn, then the form is submitted to index.php with target="somwhere". On server side I am generating pdf with value from textarea and this PDF is opened in new tab (target="somwhere" is some trick that opens pdf in new tab).
However, now I also need submit form on #doc_send_email click. In this case I also need to generate PDF, but it should be sent to provided email and then it should show confirmation message on the same page. So:
In index.php I need somehow distinguish what caused form submission (pritn_pdf_btn) or (doc_send_email). If I would be able to set some variable on #pritn_pdf_btn.click and on #doc_send_email.click and then sent it via POST, it would help. But I could not find sollution.
I need some way to submit form with target="somwhere" and without target="somwhere". Probably, there is someway on the #pritn_pdf_btn.click and on #doc_send_email.click to submit form with and without target?
It's easier to do it with multiples submit buttons like this:
<form method="post" id="doc_form" target="somwhere">
<textarea name="doc_text"><?php echo $file; ?></textarea>
<input type="hidden" name="submitted" value="1" />
<input type="submit" name="email" value="1" id="doc_send_email" class="btn" value="SEND"/>
<input type="submit" name="pdf" value="1" id="pritn_pdf_btn" class="btn" value="Print PDF"/>
</form>
Then at backend (asuming it is PHP)
if($_POST['email'])
sendEmail();
else
generatePDF();
Or by using JS:
<form method="post" id="doc_form" target="_self">
<textarea name="doc_text"><?php echo $file; ?></textarea>
<input type="hidden" name="submitted" value="1" />
<input type="hidden" name="action" id="action" value="generate" />
</form>
<a id="doc_send_email" onclick="document.getElementById('action').value='email';document.getElementById('doc_form').submit();" class="btn">SEND</a>
<a id="pritn_pdf_btn" onclick="document.getElementById('action').value='generatePdf';document.getElementById('doc_form').target='somwhere';document.getElementById('doc_form').submit();" class="btn">Print <span class="span_pdf">PDF </span></a>
Then at backend (asuming it is PHP)
if($_POST['action']=='email')
sendEmail();
else
generatePDF();

Submit button, next step

I am done with the search page where the user enters the information and select from the drop-list. I've also added the button AddList where you can have more than one search form with tag names changed. All of the searches will eventually be executed in one Submit button and each search will go in one single query. My table caries all the information and tuples contain only numbers.
UPDATED: I tried changing the input type of the input tags but the enable and disable functions can't seem to work on integers, only on text fields. How can I fix that?
My submission is tomorrow, and here is my search code:
<script type="text/javascript">
$('#exactButton').live('click', function(){
$(this).prev().prev().prev().prev().prev().removeAttr('disabled');
$(this).prev().prev().prev().attr('disabled',true);
$(this).prev().prev().prev().prev().attr('disabled',true);
});
$('#rangeButton').live('click',function(){
$(this).prev().prev().removeAttr('disabled');
$(this).prev().prev().prev().removeAttr('disabled');
$(this).prev().prev().prev().prev().attr('disabled',true);
});
})
</script>
And this is my HTML code:
<button id="button">Add List</button><br><br>
<form id ="form" name="search" method="get" action="test.php">
<div id="div">
<select name ="select" >
...options...
</select>
Value:<input type="text" name="exact" id="exactField" />
From: <input type="text" name="from" id="fromField" />
To: <input type="text" name="to" id="toField" />
<br>
<input type="button" name="answer" value="Range" id="rangeButton" />
<input type="button" name="answer" value="Exact" id="exactButton" />
</div>
<br>
<input type="submit"name="search" value="Submit">
</form>
Thank you in advance..
as Dagon said, you will see all submitted parameters in the URL since you are submitting the form with method GET. here is very good explanation for this: http://www.w3schools.com/php/php_get.asp
One idea:
add some custom attributtes to the elements (to the clones too).
this.attr("mycustomattribute","somevalue");
after this, you can get all elements on the page with your custom attribute and your value.
divs = $('div[mycustomattribute="somevalue"]'); //should give all div container with attribute "mycustomattribute" with value "somevalue"
divs.each(function(){
console.log(this,$(this).attr('name'));//show expression (for debug)
});
then you can collect this elements, serialize it and add it to your post Not tested, but an idea.
Kind Regards
In PHP, it's already there.
print_r($_GET); will list all parameters sent by GET method
print_r($_POST); will list all parameters send by POST method.
Then, of course, you will need to iterate in the array to include each values in your query statement.
You can naming input with prefix or suffix correspond to sequence that user click to add list and add those set of inputs to only form.
<form id ="form" name="search" method="get" action="test.php">
<div>
<select name ="select[1]" >
...options...
</select>
Value:<input type="text" name="exact[1]" class="exactField" />
From: <input type="text" name="from[1]" class="fromField" />
To: <input type="text" name="to[1]" class="toField" />
<br>
<input type="button" name="answer[1]" value="Range" class="rangeButton" />
<input type="button" name="answer[1]" value="Exact" class="exactButton" />
</div>
<div>
<select name ="select[2]" >
...options...
</select>
Value:<input type="text" name="exact[2]" class="exactField" />
From: <input type="text" name="from[2]" class="fromField" />
To: <input type="text" name="to[2]" class="toField" />
<br>
<input type="button" name="answer[2]" value="Range" class="rangeButton" />
<input type="button" name="answer[2]" value="Exact" class="exactButton" />
</div>
.
.
.
<br>
<input type="submit"name="search" value="Submit">
</form>

multiple submit button

i've a form POST with multiple submit buttons. i understand to get this to work i must have them with different name.
however, i wanna keep the name to be the same because i wanna handle the POST using a single script.
im not sure if there is other way but i know javascript can be used. however, how do i get the value of the hidden value associated to the button since now they have only a single ??
my example is as follows:
<form method="Post" action="file.php">
<input type="hidden" name="removeid" value="1" />
<input type="submit" id="btnremove" name="btnremove" value="Remove" inputbutton/>
<input type="hidden" name="removeid" value="2" />
<input type="submit" id="btnremove" name="btnremove" value="Remove" inputbutton/>
<input type="hidden" name="removeid" value="2" />
<input type="submit" id="btnremove" name="btnremove" value="Remove" inputbutton/>
</form>
Your hidden values are not associated with the buttons at all. Furthermore, you cannot use the same value for the ID attribute on multiple elements.
What I usually do in this situation is check the POST vars. Name them something like remove_1, remove_2, etc. Then you can search through your POST vars, find all of them beginning with remove_ (or whatever format you choose... don't use it for other things) and then you can parse out the ID of what you are trying to remove.
You could always just use 3 different forms, all with the same action. No JavaScript needed.
<form method="Post" action="file.php">
<input type="hidden" name="removeid" value="1" />
<input type="submit" value="Remove" inputbutton/>
</form>
<form method="Post" action="file.php">
<input type="hidden" name="removeid" value="2" />
<input type="submit" value="Remove" inputbutton/>
</form>
<form method="Post" action="file.php">
<input type="hidden" name="removeid" value="2" />
<input type="submit" value="Remove" inputbutton/>
</form>
It's possible using two different methods:
If you absolutely have to show 3 different buttons, use a separate <form> wrapper for each one. Put each "removeid" element in a different form.
Otherwise, just have a single button, and when submitted, use JavaScript to set the value of a single hidden input element before posting the form. You can find sample code for this easily with a Google query for "javascript+form+post".
You can have one form with more than one submit button sharing the same name, your initial assumption was wrong.
The following code is perfectly valid, and the value of the clicked submit button will be passed along with its name:
<form action="TestZone.html" method="GET">
<input type="submit" name="MySubmit" value="First" /><input type="submit" name="MySubmit" value="Second" /><input type="submit" name="MySubmit" value="Third" />
</form>
You can't have multiple elements with same ID, but same name for form elements is common and valid.
Hi i have resolved my questions by following Brad solution. to get the POST var, i did this:
//Check if Remove btn is clicked
$isClickRemove = false;
$cid = "";
foreach($_POST as $k=>$v){
$pos = strpos($k,"btnremovecart_");
if($pos !== false){
$pos2 = strpos($k,"_"); //2nd pos to get cartID
$cid = substr($k,$pos2+1);
$isClickRemove = true;
break;
}
}
my html looks like this:
<input type="submit" id="btnremovecart_11" name="btnremovecart_11" value="Remove" />
hope this helps =)
You can't because there is no way of distingushing the different fields.

how to pass values from one page to another on jquery form submit

I'm trying to build a form using php & jquery, but I'm a little confused as to what to do with the jquery portion of it...
Basically, when the user submits the first form, I want to direct them to the "next step" form, but I want to retain the values submitted from the first one in a hidden input field...
If someone can either show me how or point me to a good tutorial, I'd appreciate it...
I don't have any of the php or jquery yet, and this is just a simplified version of the html markup...
//first.php
<form name="form1" method="post" action="second.php">
<input type="text" name="name" value="" />Name
<input type="submit" name="step1" value="Next" />
</form>
//second.php
<form name="form2" method="post" action="process.php">
<input type="hidden" name="name" value="{$_POST['name']}" />
<input type="text" name="message" value="" />message
<input type="submit" name="step2" value="Finish" />
</form>
<input type="hidden" name="name" value="{$_POST['name']}" />
should be,
<input type="hidden" name="name" value="<?php echo $_POST['name']}; ?>" />
and also sanitize the input, if you want
I don't no if there is a better way to do that.
But, when I need to do such thing, I do in this way:
<script>
<?php
foreach($_POST as $key => $valule)
{
echo "$('$key').val('$value')";
}
?>
</script>
So, in your nextstep file, all you'll need to do is set up the hidden fields and then just loop through the post vars and set each one via jquery.

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