Loop - Accept multiple times input from a single textbox name in PHP - php

(this might get confusing) i have 2 textboxes which would accept color and amount from a user ten times:
<form action="" method="POST">
<i> color </i><input type="text" name="text[]">
<i> color amount </i> <input type="number" name="num[]">
<input type="submit" value="Go">
</form>
Now what i want to happen is that instead of declaring ten text boxes for color and amount i would just want to loop it so that after the first color and amount had been sent it would again ask for 9 times without displaying 10 textboxes for each name. Is there a way in php to loop it?
Thanks.
Regars,
Russel

#russel
try this. This one is in pure php.
<html>
<head>
<title></title>
</head>
<body>
<?php
session_start();
if(!isset($_POST['submit']))
{
$_SESSION['count']=0;
}
?>
<form action="" method="POST">
<i> color </i><input type="text" name="text">
<i> color amount </i> <input type="number" name="num">
<input type="submit" value="Go" name="submit">
</form>
<?php
if(isset($_POST['submit']))
{
echo $_POST['text'];
echo "<br>";
echo $_POST['num'];
echo "<br>";
$count=$_SESSION['count']++;
if($count==9)
{
echo "you have received 10 values";
echo "<br>";
echo "press ok to get again";
?>
<form method="post">
<input type="submit" name="ok" value="ok">
</form>
<?php
if(isset($_POST['ok']))
{
header("Refresh:0");
}
}
}
?>
</body>
</html>

I would use Ajax. You can store a counter variable in JS and when it reaches 10 you just disable the form or show a message to the user.
jQuery.post()
If Ajax is not an option you always can have the counter in your PHP file. I would sugget storing it in a session. Then when counter reaches 10 you just dont echo the form or something.
session_start();
$_SESSION['counter'] = (!$_SESSION['counter']) ? 0 : $_SESSION['counter'];
if($_POST['submit']) {
$_SESSION['counter']++;
}
EDITED: a basic idea (not tested yet) I would use button.click to avoid any kind of form submision
<form id="myForm" method="post">
<i> color </i><input type="text" name="text[]">
<i> color amount </i><input type="number" name="num[]">
<input id="button" value="OK" type="button">
</form>
<script>
var formCounter = 0;
$("#button").click(function(e) {
var url = ""; // Whatever
alert("OK");
$.ajax({
type: "POST",
url: url,
data: '', // Your data here
success: function(data) {
// Do you need to show confirmation?
formCounter++;
if(formCounter > 9){
// Disable/Hide form here
}
}
});
e.preventDefault();
});
</script>

Related

Hide a form field with a specific id after submit

I'm new here and a super noob in programming. I'm having trouble with my project. My problem is that I'd like hide the form after submit and retain the data input in it.
Here's my code:
<?php
$displayform = true;
if (isset($_POST['trck']))
{
$track = addslashes(strip_tags($_POST['tracknumber']));
$ord = $_POST['id'];
$displayform = false;
if (!$track)
echo "Please enter your tracking number!";
else
{
mysql_query("update `orderdetails` set `trackno`='$track' where `id`='$ord'");
}
if ($row2['id']==$ord)
echo $_POST['tracknumber'];
}
if ($displayform)
{
?>
<form method="post" action="">
<input type="text" name="tracknumber" id="tracknumber" size="30" maxlength="30" placeholder="Enter your track number here." />
<input type="hidden" name="id" value="<?php echo $row2['id']; ?>">
<input type="submit" name="trck" id="trck" value="Save" onclick="return confirm(\'Are you sure you want to save this tracking number?\');" />
</form>
</td>
</tr>
<?php
}
}
?>
This code was inside a while loop and my problem with this is that after I submit all the form is hidden. All I want is to hide the form with the specific ID on a query.
Simplest way is to use jQuery hide
Include the jquery as
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
$("#buttonid").click(function(){
$("#formid").hide();
});
You are looking for something like this in your <form> tag:
<form method="post" action="" id="awesome_form" onSubmit="document.getElementById('awesome_form').style.display = 'none';">
use the jQuery and use :
$("#submitButtonId").click(function(){
$('#formId').hide();
});
or else in pure javascript use
<input type="submit" value="submit" onClick="hideIt()"/>
<script type="text/javascript" >
function hideIt() {
document.getElementById('formId').style.display = 'none';
}
</script>
its better not to use inline javascript

Transfer javascript variable to php using hidden forms?

I have a form on my page that asks users to enter in their height/weight and it calculates their BMI and stores it in a database. I am hung up on how I transfer the javascript variable to a php variable. I understand I have to use hidden forms but I can't seem to figure out how they work.
here is my code
<?php include "base.php"; ?>
<?php session_start (); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>BMI</title>
</head>
<body>
<form id="bmi" action="main.php" method="post">
<p>Enter your height(in inches):</p><input type="text" id="height box" name="height box">
<p>Enter your weight(in pounds):</p><input type="text" id="weight box" name="weight box">
<input type="hidden" id="bmi" name="bmi">
<input type="button" value="Calculate" id="calc button" name="calc button" onClick="calc()">
</input>
</form>
<script type="text/javascript">
function calc()
{
// get variables from textboxes
var height=document.getElementById('height box').value;
var weight=document.getElementById('weight box').value;
var bmi=document.getElementById('bmi').value;
// calculate BMI
weight/=2.2;
height/=39.37;
BMI=Math.round(weight/(height*height));
</script>
<?php
//insert username, date, and bmi into the db
$username = mysql_real_escape_string($_SESSION['Username']);
$date = date('Y-m-d');
$bmi = mysql_real_escape_string($_POST['bmi']);
mysql_query("INSERT INTO bmi (username, bmi, date) VALUES('".$username."', '".$bmi."', '".$date."')");
?>
</body>
</html>
base.php is just where I do my connect to the sql server and select the database stuff
The javascript bmi variable does not seem to be transferring to the php $bmi variable. What is it I am doing wrong?
Set the value of the hidden input bmi to the calculated value.
<form id="bmi" action="main.php" method="post">
<p>Enter your height(in inches):</p><input type="text" id="height box" name="height box">
<p>Enter your weight(in pounds):</p><input type="text" id="weight box" name="weight box">
<input type="hidden" id="bmi" name="bmi">
<input type="submit" value="Calculate" id="calc button" name="calc button" onClick="calc()">
</form>
<script type="text/javascript">
function calc()
{
// get variables from textboxes
var height=document.getElementById('height box').value;
var weight=document.getElementById('weight box').value;
var bmi=document.getElementById('bmi').value;
// calculate BMI
weight/=2.2;
height/=39.37;
document.getElementById('bmi').value=Math.round(weight/(height*height));
}
</script>
Since you are not displaying the bmi to the user before he submits the form, make life easy for yourself. Use php code to calculate the bmi instead of javascript.
A few problems I see in your code:
In HTML you cannot have id and name attributes with spaces (http://www.w3.org/TR/html4/types.html#type-id)
You are calculating the bmi but aren't assigning it to the form element.
You are missing closing brace on the javascript calc() function.
The solution would be to fix the id attribute first, for e.g you could use camel case notation like follows:
<form id="bmi" action="main.php" method="post">
<p>Enter your height(in inches):</p><input type="text" id="heightBox" name="heightBox">
<p>Enter your weight(in pounds):</p><input type="text" id="weightBox" name="weightBox">
<input type="hidden" id="bmi" name="bmi">
<input type="submit" value="Calculate" id="calcButton" name="calcButton" onClick="calc()">
</form>
Update the javascript like follows:
function calc()
{
// get variables from textboxes
var height=document.getElementById('heightBox').value;
var weight=document.getElementById('weightBox').value;
var bmi=document.getElementById('bmi');
// calculate BMI
weight/=2.2;
height/=39.37;
bmi.value=Math.round(weight/(height*height));
}
Another point to note is that you are using mysql_ extensions which are deprecated. You want to start using mysqli or PDO instead.
I have simplified your code to 3 parts for better understanding, hopefully:
HTML: I'm using GET method instead of POST to see the variable on the URL. Please also not that input does not have close bracket </input>
<form action="index.php" method="GET">
<input type="text" name="height">
<input type="submit" onclick="calc();">
</form>
JavaScript: window.location.href tells the browser to show the variable on the URL
function calc(){
var height = document.getElementById('height').value;
window.location.href = "index.php?height=" + height;
}
</script>
PHP: Now you can retrieve the variable by using $_GET['height']
<?php
$height = $_GET['height'];
echo $height;
?>

Display message including the session name

Is there a way, when clicking on a button, using HTML and PHP, to display an alert message containing the name of the session started, a radio button checked and the date and time choose? The button is included in a form, so I am looking if there is way to get these things done...
Here's my code:
<?php
if (!isset($_SESSION)) {
session_start();
}
echo $_SESSION["uname"]; ?>
</div>
<br>
<form id="form1" action="welcome.php" method="post" >
Blood Type Needed :
<br>
<br>
<input id="input1" type="Radio" value="A+" name="bn"/> A
<input id="input1" type="Radio" value="B+" name="bn"/> B
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
$('input[#name="bn"]:checked').val();
var radios = document.getElementsByName('bn');
if (radios.checked) {
function showSession(){
var x=document.getElementById("sessionId");
var y=new Date();
alert(x.value+" wants "+radios.value+y);
}
}
</script>
<input id="done" class="button1" type="button" onClick="showSession();" value=" DONE ">
</form>
I will use a INPUT hidden and a javascript function, after attack it to onClick event on your button, but suggest you use Jquery to make all cross-browser:
HTML input
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
JAVASCRIPT
function showSession(){
var x=document.getElementById("sessionId");
alert(x.value);
}
HTML BUTTON
<input type="button" value="Click me" onClick="showSession();" />
FULL SCRIPT
<?php
if (!isset($_SESSION)) session_start();
echo "Session ID: ".$_SESSION["uname"];
?>
</div><br/>
<script>
function showData(){
var sessionId = document.getElementById("sessionId").value;
var today = new Date();
var x = document.getElementsByName('bn')
var selected = false;
// Check the selected value
for(var k=0;k<x.length;k++)
if(x[k].checked){
alert(' '+ sessionId + " wants " + x[k].value + " " +today);
selected = true;
}
if (!selected) alert('Select something please...');
}
</script>
<form id="form1" action="welcome.php" method="post" ><br/>
Blood Type Needed :<br/><br/>
<input id="AP" type="Radio" value="A+" name="bn"/><label for="AP"> A</label><br/>
<input id="BP" type="Radio" value="B+" name="bn"/><label for="BP"> B</label><br/><br/>
<input id="done" type="button" onClick="showData();" value=" DONE " class="button1">
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
</form>
You can do this by using simple Javascript
<script>
function showValue()
{
var sessionVal=<?php echo $_SESSION['uname']; ?>;
var selectedDate=documnet.form1.dt.value;
var selectedRadio=document.form1.bn.value;
alert(sessionVal+" "+selectedRadio+" "+selectedDate); //what ever format you want to show.
document.form1.actiom='welcome.php';
document.form1.submit();
}
</script>
In your html add onsubmit function
<form id="form1" action="" onsubmit="return showValue();" method="post" >

2 forms with one PHP file

I have 2 FORMS on a single page, One below the other.
I would like to have such that second form should be always in disable mode.
and Once the first form submit button is pressed and validated second should get activated to enter the data in it.
Is there anything in PHP which can help me on this
You have 2 ways:
1) send validation of first form using ajax, and, if you receive 'true', enable second form.
2) make a POST from first form, if everything is good, set "validated" to 'true' and reload the same page. In the second form "enabling" must be only if you have $validated = true;
The logic below should help you out as a starting point:
<form method="post">
<input type="text" name="name" />
<input type="submit" name="form1" value="Proceed" />
</form>
<form method="post">
<input type="text" name="email"<?php if(!isset($_POST['form1'])) { echo ' disabled="disabled"'; } ?> />
<input type="submit" name="form2" value="Submit"<?php if(!isset($_POST['form1'])) { echo ' disabled="disabled"'; } ?> />
</form>
Of course, it would be much more reliable to use either AJAX to validate the first form, or to have the forms appear on separate pages.
<?php
if(isset($_POST['next'])) {
if($_POST['name']!="") {
$disabled = "";
$val = $_POST['name'];
} else {
$disabled = " disabled='disabled'";
$val="";
}
} else {
$disabled = " disabled='disabled'";
$val="";
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form id="frm1" name="frm1" method="POST" action="">
<label>Name</label><input type="text" id="name" name="name" value="<?php echo $val;?>"/>
<input type="submit" name="next" id="next_frm" value="Next"/>
</form>
<form name="frm2" id="frm2" method="POST" action="">
<label>Address</label><input type="text" name="address" id="address" value="" <?php echo $disabled;?>/>
<input type="submit" name="save" id="save" value="Save" <?php echo $disabled;?>/>
</form>
</body>
</html>
This is somewhat you were looking for ,I hope
You can do it by setting a class on all inputs within second form and set them as disabled of course someone who knows a bit of javascript will be able to change it.
So you can do it as your visual layer, but then check in PHP as well if second form can be passed in case someone wanted to sneak something in.
More complicated approach would be to show images that look like form fields and only change them to inputs where the first form is submitted. That can be done on client or server side
So in reality you will have 3 forms, but one would be "fake"
Thats simple just use if else condition.
// this if condition checks whether the form 1 is submitted or not. If form1 is submitted than form 2 is displayed else form1 wil only be displayed
if(isset($_POST['submit']))
{
//Display your form 2.
}
else
{
//Display your form1.
}

Unlimited fields in PHP?

How do I do unlimited fields in php? Here is the scenario:
At first, there are only 2 fields, lets called: first name1, last name1
What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..
Can anyone give me some sample script in php? I am new to PHP.
The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.
That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.
Simple Javascript (jQuery) Example:
$(document).ready(function(){
$("input[value='Add']").click(function(event){
event.preventDefault();
$("p.field:last").clone().insertAfter("p.field:last");
});
});
<form method="post">
<p class="field">
<input type="text" name="firstname[]" value="" />
<input type="text" name="lastname[]" value="" />
</p>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
Simple PHP Example:
I don't encourage you use this as-is
<?php
$count = 1;
if ($_POST["submit"] == "Add") {
$count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;
} else
if ($_POST["submit"] == "Done") {
print "<pre>";
print_r($_POST["firstname"]);
print_r($_POST["lastname"]);
print "</pre>";
}
?>
<form method="post">
<?php for($i = 0; $i < $count; $i++) { ?>
<p class="field">
<input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" />
<input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
</p>
<?php } ?>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.
A general outline of the solution is this:
Initially $count is 1, and one row is generated.
If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
If the user clicks Submit, the names that have been entered are processed.
Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Categories