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;
?>
Related
(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>
On my web page, when I press the "Add Customer" link, the following happens:
the onclick handler is called, which
sets values into the forms two text fields
displays an alert (at this point you can see the new values in the text fields on the screen)
calls the form's submit button (Note: the form submits back to it's own PHP file)
The same php file is called, but there are no POST values received
I've verified this with
the code in the first line that counts the values in $_POST then displays later
using fiddler to look at the request sent to the page
I've done this type of thing numerous times before with no problems. I've copied this code to two different web servers (linux, apache) with the same result. It's probably a minor problem but I can't find it.
I've stripped out a whole bunch of code to get down to this little bit, but haven't figured out why no POST values are being sent.
You can see a working copy of this at http://www.daleann.org/dla.php. The only thing need besides the code below is /js/jquery.min.js.
Thanks for your help.
<?php
$pc=count($_POST)."<br />".date("H:i:s");
?>
<html>
<head>
<script src="/js/jquery.min.js" /></script>
<script type="text/javascript">
$(document).ready(function() {
alert("inside docReady");
$(document).on('click', "a.menuBillingOwner", function() {
$("#selectedBillingOwner").val("11");
$("#lastCustomNavSelected").val("selectedBillingOwner");
alert("selectedBillingOwner = "+document.forms['formBillingOwner'].elements['selectedBillingOwner'].value);
document.forms['formBillingOwner'].submit();
});
});
</script>
</head>
<body>
<ul id="menuBillingOwner">
<li><a href='#' id='menuBillingOwnerAdd' class='menuBillingOwner'>Add Customer</a></li>
</ul>
<?php
$lastCustomNavSelected = $selectedBillingOwner = "";
if (count($_POST) > 0 && isset($_POST['selectedBillingOwner'])) {
$lastCustomNavSelected = "selectedBillingOwner";
$selectedBillingOwner = $_POST['selectedBillingOwner'];
}
?>
<?php echo "pc = ".$pc."<br />\n"; ?>
<form name="formBillingOwner" id="formBillingOwner" method="POST" action="/dla.php">
<input type="text" id="lastCustomNavSelected" value="<?php echo $lastCustomNavSelected; ?>" />
<input type="text" id="selectedBillingOwner" value="<?php echo $selectedBillingOwner; ?>" />
</form>
</body>
</html>
Simple, because your form fields don't have name attributes, see below
<form name="formBillingOwner" id="formBillingOwner" method="POST" action="/dla.php">
<input type="text" id="lastCustomNavSelected" value="<?php echo $lastCustomNavSelected; ?>" />
<input type="text" id="selectedBillingOwner" value="<?php echo $selectedBillingOwner; ?>" />
</form>
Add names to them, for example:
<form name="formBillingOwner" id="formBillingOwner" method="POST" action="/dla.php">
<input type="text" id="lastCustomNavSelected" name="lastCustomNavSelected" value="<?php echo $lastCustomNavSelected; ?>" />
<input type="text" id="selectedBillingOwner" name="selectedBillingOwner" value="<?php echo $selectedBillingOwner; ?>" />
</form>
Note: Probably your jQuery assignments need to be fixed too but if that was the only issue then atleast a wrong value should have been POSTed to PHP, hence that is not the issue.
Delete these 2 lines of your jQuery.
$("#selectedBillingOwner").val("11");
$("#lastCustomNavSelected").val("selectedBillingOwner");
because that will change the value of textfield before your submit the form
I use daterangepicker() to get two dates ( begginning and ending ), I'd like to put those dates in php variables.. i've succeeded to do an alert() to show those variables using a button.. but i don't know how to put them in the php.
here's my code if anyone have an idea..
<script type="text/javascript">
$(function(){
$('#rangeBa, #rangeBb').daterangepicker();
});
function test(){
var dates = new Array();
dates[0] = document.inputdate.rangeBa.value;
dates[1] = document.inputdate.rangeBb.value;
return dates;
}
</script>
<body>
<form name="inputdate" method="post">
<input type="text" value="m/jj/aaaa" id="rangeBa" name="rangeBa"/>
<input type="text" value="m/jj/aaaa" id="rangeBb" name="rangeBb"/>
</form>
<button onclick="alert(test())">Click on this button</button>
</body>
You have to add a submit input element in your form and add an action parameter in your form:
<form name="inputdate" method="post" action="yourfile.php">
<input type="text" value="m/jj/aaaa" id="rangeBa" name="rangeBa"/>
<input type="text" value="m/jj/aaaa" id="rangeBb" name="rangeBb"/>
<input type="submit" value="Click to send" />
</form>
And in yourfile.php: you get the variables by $_POST['rangeBa'] and $_POST['rangeBb']
Feel free then to use ajax method if you don't want a refresh of the page.
After you submit your form you can find the form variables by name in $_POST. for example $_POST['rangeBa']
I have several forms on a page and they have to be filled in automatically by accessing a users ID and then filling the rest of the text boxes with the necessary information. Essentially an auto fill for the forms dependent on which RFID is entered into the first text box.
<html>
<head>
<?php
$con = mssql_connect("123", "abc", "pass");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM Scrabble");
$row = array("RFID" => "", "Tile" => "", "TileScore" => "");
$row = mssql_fetch_row($result)
?>
</head>
<body>
<form>
<input type="text" name="RFID1"/>
<input type="text" name="Tile1"/>
<input type="text" name="TileScore1"/>
<input type ="button" value="submit" onclick="RFID1.disabled=true" />
<td><input type="text" name="RFID2"/>
<input type="text" name="Tile2"/>
<input type="text" name="TileScore2"/>
<input type ="button" value="submit" onclick="RFID2.disabled=true" />
<input type="text" name="RFID3"/>
<input type="text" name="Tile3"/>
<input type="text" name="TileScore3"/>
<input type ="button" value="submit" onclick="RFID3.disabled=true" />
<form>
</body>
</html>
I need it to take the Tile and TileScore from where the RFID is equal to what is entered in the text box. Is this possible without having to submit the page to allow the other forms to be filled in as well? I've been told it may be possible using AJAX but am unaware of a solution.
This is using MSSQL, sadly there isn't an MSSQL tag.
Disclaimer
I'm assuming that the way you want your page to function is that the user types into the RFID text-field.
To make the code simpler and more flexible I've changed the three form-like segments into three separate forms. This also has an added advantage that if the browser doesn't support JavaScript the page falls back to submitting the form.
I could not make sense of the SQL so I have merely commented it out.
I have also added some extra PHP throughout the page, so that in case of javascript not being available the submitted page will still respond with the form correctly.
To add in your SQL query code, just make sure the resulting Tile and TileScore are placed in variables $tile and $tileScore respectively.
Code
<?php
/*
function sqlStuff(){
$con = mssql_connect('123', 'abc', 'pass');
if(!$con){die('Could not connect: ' . mssql_get_last_message());}
mssql_select_db('db1', $con);
$result = mssql_query('SELECT * FROM Scrabble');
// Why is the following here?
$row = array('RFID' => '', 'Tile' => '', 'TileScore' => '');
$row = mssql_fetch_row($result)
}
*/
$rfid=$_GET['RFID'];
$tile='Tile for "'.$rfid.'"';
$tileScore='TileScore for "'.$rfid.'"';
$separ='/'; //separator
// if this is an ajax request do the following, if not print the page as normal
if($_GET['r']=='ajax'){
$ajaxString=$separ.$tile;
$ajaxString.=$separ.$tileScore;
echo $ajaxString;
}else{
// which form was submitted, only used if form was submitted by browser.
$form=$_GET['form'];
// escape quote characters
$rfid=htmlentities($rfid);
$tile=htmlentities($tile);
$tileScore=htmlentities($tileScore);
?><?xml version="1.0" encoding="UTF-8"?>
<!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>live-submitting form using javascript!</title>
<style type="text/css">
/*<![CDATA[*/
body{font:80% sans-serif;}
/*]]>*/
</style>
<script type="text/javascript">
//<![CDATA[
window.onload=load;
function load(){
document.getElementById('form1').onsubmit=function(){if(submitWithJS(this)){return false;}};
document.getElementById('form2').onsubmit=function(){if(submitWithJS(this)){return false;}};
document.getElementById('form3').onsubmit=function(){if(submitWithJS(this)){return false;}};
}
function submitWithJS(thisForm){
// setup ajax object
var httpReq;
if(window.XMLHttpRequest){// Non-IE
httpReq=new XMLHttpRequest();
}else if(window.ActiveXObject){ // IE
try{httpReq=new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){
try{httpReq=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){
return false; // some other IE check?
}
}
}else{
return false; // submit without ajax
}
// Actual code:
httpReq.onreadystatechange=function(){
// basically readyState 4 is when reply is recieved
if(this.readyState==4){responder(this,thisForm);}
}
// prepare args
//beware "arguments" is a keyword
var args="?r=ajax"; // type of request
args+="&RFID="+thisForm.RFID.value;
// begin request
httpReq.open("GET",args);
httpReq.send();
return true;
}
function responder(httpResponse,form){
// use the $separ variable from PHP
<?php echo ' var separator="'.$separ.'";'."\n";?>
if(httpResponse.responseText[0]==separator){
var returned=httpResponse.responseText.split(separator); // separation
form.Tile.value=returned[1];
form.TileScore.value=returned[2];
}else{form.submit();}
}
//]]>
</script>
</head>
<body>
<p class="notice">javascript required to use more than one form</p>
<form method="get" action="" id="form1">
<div>
<input type="hidden" name="form" value="1"/>
<input type="text" name="RFID"<?php if($form==1){echo ' value="'.$rfid.'"';}?>/>
<input type="text" readonly="readonly" name="Tile"<?php if($form==1){echo ' value="'.$tile.'"';}?>/>
<input type="text" readonly="readonly" name="TileScore"<?php if($form==1){echo ' value="'.$tileScore.'"';}?>/>
<input type ="submit" value="submit"/>
</div>
</form>
<form method="get" action="" id="form2">
<div>
<input type="hidden" name="form" value="2"/>
<input type="text" name="RFID"<?php if($form==2){echo ' value="'.$rfid.'"';}?>/>
<input type="text" readonly="readonly" name="Tile"<?php if($form==2){echo ' value="'.$tile.'"';}?>/>
<input type="text" readonly="readonly" name="TileScore"<?php if($form==2){echo ' value="'.$tileScore.'"';}?>/>
<input type ="submit" value="submit"/>
</div>
</form>
<form method="get" action="" id="form3">
<div>
<input type="hidden" name="form" value="3"/>
<input type="text" name="RFID"<?php if($form==3){echo ' value="'.$rfid.'"';}?>/>
<input type="text" readonly="readonly" name="Tile"<?php if($form==3){echo ' value="'.$tile.'"';}?>/>
<input type="text" readonly="readonly" name="TileScore"<?php if($form==3){echo ' value="'.$tileScore.'"';}?>/>
<input type ="submit" value="submit"/>
</div>
</form>
</body>
</html>
<?php }?>
Since you're trying to fill text fields on the page based on the input of another text field on the page, you need AJAX or to dump all possibilities of the text fields into javascript variables on the page from PHP (ew).
http://api.jquery.com/jQuery.ajax/
Have it call a PHP script that returns a JSON object that holds the field data based on the RFID text field.
I'm trying to build a form which submits a URL which contains a lon/lat that has been passed over from Google Maps. I have managed to get it so the lon/lat is passed into input fields in the form, how would I go about using these values dynamically in the post URL, i.e.:
action="search.asp?[lon][lat]
If you want to get the values from the form into the URL, set the method attribute to get:
<form method="search.asp" action="get">
. This will put the values of the lon and lat fields of the form in the URL. Example:
search.asp?lat=[lat value]&lon=[lon value]
For more information, read this page. Excerpt:
If the processing of a form is
idempotent (i.e. it has no lasting
observable effect on the state of the
world), then the form method should be
GET. Many database searches have no
visible side-effects and make ideal
applications of query forms.
Using javascript you can change the action attribute of the form. So, create a form..
<form name="myForm">
<input type="hidden" name="lon" value="123" />
<input type="hidden" name="lat" value="321" />
...
<button onclick="setAction();">Submit</button>
</form>
Then in the head of the page add the setAction function..
<script type="text/javascript">
function setAction()
{
var lon = document.myForm.lon.value;
var lat = document.myForm.lat.value;
document.myForm.action = "search.php?["+lat+"]["+lon+"]"';
document.myForm.submit();
}
</script>
Hope this helps, it's how I have done this in the past!
Try using:
<form action="search.php" method="get">
<input type="hidden" name="lon" value="<?php echo $lon_fromGoogleMaps; ?>" />
<input type="hidden" name="lat" value="<?php echo $lat_fromGoogleMaps; ?>" />
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>
Or if you want to use the form as post:
<form action="search.php?lon=<?php echo $lon_fromGoogleMaps; ?>&lat=<?php echo $lat_fromGoogleMaps; ?>" method="post">
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>
I see you tagged this as Javascript as well, and as Google Maps relies heavily on Javascript, you may have the Lon and the Lat passed as Javascript variables...
<script type="text/javascript">
// Obviously, execute this code after the DOM has loaded...
var formAction = document.searchForm.action;
formAction = formAction + '?lon=' + lon_fromGoogleMaps + '&lat=' + lat_fromGoogleMaps;
document.searchForm.action = formAction;
</script>
<form action="search.php" method="post" name="searchForm">
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>