Error upon form submission in php - javascript

It appears my information is not being placed into the POST array correctly. I'm new to php so I'm not too sure why. I don't know what other information y'all need on this, so I'll just place the code and the error message. Any help/advice you could offer would be greatly appreciated.
This is the form after being rendered.
This is the error I'm getting after submission.
Here's the code snippets. I haven't included all of the html. I may be that I need to ditch the php and write stuff in java. Opinions welcomed.
<h2 class="tgminix-padding-large" style="margin:auto;max-width:1000px">Calculating Total Percent Impedance Upstream of the Motor</h2>
<hr class="tgminix-border-grey" style="margin:auto;width:80%">
<p><span class="error">* Required Field</span></p>
<form method="post" action="<?php echo htmlspecialcharachars($_SERVER["PHP_SELF"]);?>
High Side Busbar Impedance (Real): <input type="float" name="SubstationHighsideEqivImpedanceR">
<span class="error"> <?php echo $subImpedanceError;?></span>
<br><br>
High Side Busbar Impedance (Imaginary): <input type="float" name="SubstationHighsideEqivImpedanceI">
<span class="error"> <?php echo $subImpedanceError;?></span>
<br><br>
Low Side Busbar Impedance (Real): <input type="float" name="SubstationLowsideEquivImpedanceR">
<span class="error"><?php echo $subImpedanceError;?></span>
<br><br>
Low Side Busbar Impedance (Imaginary): <input type="float" name="SubstationLowsideEquivImpedanceI">
<span class="error"><?php echo $subImpedanceError;?></span>
<br><br>
Motor Starting Power Factor: <input type="float" name="MotorStartingPowerFactor_num">
<span class="error"><?php echo $subImpedanceError;?></span>
<br><br>
<input type="submit" value="Submit">
</form>
<?php
/* Locked Rotor Constants Array
$MotorLockedRotorConstants = array(
array("NEMA Code Letter","Mid-Value Constant")
array("A",1.6)
array("B",3.3)
array("C",3.8)
array("D",4.3)
array("E",4.7)
array("F",5.3)
array("G",5.9)
array("H",6.7)
array("J",7.5)
array("K",8.5)
array("L",9.5)
array("M",10.6)
array("N",11.8)
array("P",13.2)
array("R",15.0)
array("S",17.1)
array("T",19.0)
array("U",21.5)
array("V",25));*/
if ($_POST){
$SubstationHighsideEqivImpedance_real = $_POST["SubstationHighsideEqivImpedanceR"];
$SubstationHighsideEquivImpedance_imaginary = $_POST["SubstationHighsideEqivImpedanceI"];
$SubstationLowsideEquivImpedance_real = $_POST["SubstationLowsideEquivImpedanceR"];
$SubstationLowsideEquivImpedance_imaginary = $_POST["SubstationLowsideEquivImpedanceI"];
$MotorStartingPowerFactor = $_POST["MotorStartingPowerFactor_num"];
$SubstationPercentImpedance = "";
$TEMP_X_perc = $TEMP_R_perc = "";
$TEMP_X_perc = $SubstationLowsideEquivImpedance_imaginary + 0.333333 * $SubstationHighsideEquivImpedance_imaginary;
$TEMP_R_perc = $SubstationLowsideEquivImpedance_real + 0.33333 * $SubstationHighsideEqivImpedance_real;
$RAD_ANGLE_TEMP = $MotorStartingPowerFactor*(pi()/180);
$DEG_ANGLE_TEMP_cos = (180/pi()) * cos($RAD_ANGLE_TEMP);
$DEG_ANGLE_TEMP_sin = (180/pi()) * sin($RAD_ANGLE_TEMP);
$SubstationHisideImpedancePercent = ($TEMP_R_perc * $DEG_ANGLE_TEMP_cos) + ($TEMP_X_perc * DEG_ANGLE_TEMP_sin);
} else {
echo "There's nothing in POST. srry"
}
?>
<p class="tgminix-padding-large" style="margin:auto;max-width:1000px">
The Substation Impedance is: <?php echo $SubstationHisideImpedancePercent; ?>
<br>
The Substation Impedance is: <?php echo $TEMP_R_perc; ?> $ + \mathbf{i}$ <?php echo $TEMP_X_perc; ?>
</p>
Let me know if this is too ambiguous.

REPLACE
<form method="post" action="<?php echo htmlspecialcharachars($_SERVER["PHP_SELF"]);?>
WITH
<form method="post" action="<?php echo htmlspecialcharachars($_SERVER["PHP_SELF"]);?>">

Related

How to call php function on submit on the same page while action redirects to another page

i have a problem. I want to execute a php function on submit but the php function HAS to be on the same page because of a multi dimensional array foreach loop. So in easy terms input type="submit" action="post only $orderid to ideal.php" onclick="phpFunction on same page"
Here is my code:
$total =0;
$b = 0;
$items = array();
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_qty = $cart_itm["product_qty"];
$pid = $cart_itm["product_code"];
$results = mysql_query("SELECT * FROM Products WHERE ProductID = '".$pid."'");
while($row = mysql_fetch_array ($results)) {
$naam = $row["ProductName"];
$liters = $row["ProductLiters"];
$kleur = $row["ProductColor"];
$product_price = $row["ProductPrice"];
$beschrijving = $row["ProductDescription"];
$image = $row["ProductImage"];
$merk = $row["SupplierID"];
}
$items[] = array('pid' => $pid, 'qty' => $product_qty);
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
?>
<div class="'.$bg_color.'">
<h1 class="ptitel" id="ptitel"><?= $naam ?></h1>
<p class="prijs" id="prijs">€<?= $product_price ?> x <?= $product_qty ?></p>
<p class="verzenden">Geen verzendkosten binnen Nederland</p>
<p id="pinfo"><?= $beschrijving ?></p>
<div id="liter">
<p class="text">Liters: <?= $liters ?></p>
</div>
<div id="kleur">
<p class="text">Kleur: <?= $kleur ?></p>
</div>
</div>
<?php
}
?>
</div>
<div class="left">
<?php
---------THIS HAS TO BE EXECUTED-----------
$orderid = mt_rand(100000,900000);
foreach ($items as $key => $value) {
mysql_query("INSERT INTO Bestellingen (pid, qty, orderid) VALUES ('".$value['pid']."', '".$value['qty']."', '".$orderid."')");
}
------------------END----------------------
?>
<form method="post" action="test.php">
<input type="text" name="realname" id="name" placeholder="Volledige naam" required/>
<input type="text" name="postcode" id="postcode" placeholder="Postcode" required/>
<input type="text" name="adres" id="adres" placeholder="Straatnaam+huisnummer" required/>
<input type="text" name="plaats" id="plaats" placeholder="Plaats" required/>
<input type="tel" name="telefoon" id="telefoon" placeholder="Mobiel nummer" required/>
<input type="email" name="email" id="email" placeholder="mail#voorbeeld.com" required/>
<textarea name="Message" placeholder="Heeft u wat te vertellen?"></textarea>
<input type="text" name="discount" id="discount" placeholder="Kortingscode"/>
<input type="submit" name="betaal" class="knop" value="BETALEN €<?= $total ?>" />
</form>
1. you can use ajax to post form date to any page.
2. you can use js to update action in form tag according to you convenience.
Extra suggestion : use tag <?php ?>

How to do a page refresh after submitting and executing an update statement to show the updated values?

I have to click on the update button and then do an update in database and a refresh to show the updated values on the same page. These values must be updated in the database as well. I have been trying to do the refresh but it does not work. Need some help and guidance. Is there any other alternative besides page refresh? Can it be done without page refresh?
<?php
//initalizing the query
$id = $_GET['id'];
$query = "SELECT * FROM new_default_reports WHERE id = '$id'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" onclick="window.location.reload();"/>
</form>
</div>
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
header("Refresh: 0; url=previewgraphs.php?id=".$id);
}
?>
UPDATED:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="previewgraphs.php?id=$id" method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
Please take updated value from the database after update query.
Please try this code :-
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
$select_query = "SELECT * FROM new_default_reports where id = $id";
$select_result= $conn->query($select_query );
$row = $select_result->fetch_assoc();
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
The header function does not work in your case because you have already output before trying to set the header.
The solution is to reverse the php and html code such that the php code is on the very beginning of the document.
Little side note, now you actually do not need the refresh anymore.
EDIT included select query.
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
//header("Refresh: 0; url=previewgraphs.php?id=".$id);//not needed
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
$row = $select_result->fetch_assoc();
}
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
And remove onclick="window.location.reload();"
Here is how I would do it:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold"">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_axis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
So you wouldn't need to refresh the page, but rather you send the form to itself. It will result in another request. If the form has been sent the php code in the if-clause get executed and the database will be updated. Than you have the task to make a select query to get the updated result and display it on the page.
Should the user open the page with the form per get request, she is not going to see any results from the database.
When writing HTML you should also try to be consistent and keep the code conventions throughout your project. For single tags XML-like style is <input \>, HTML-style is <input>.
I hope this helps you and also gives you some alternative view how to solve your problem.
EDIT:
I removed the onclick event from your input element and added a submit button. When checking if the form has been sent, look for the submit button in your if-clause. If you like you can use <button type="submit">Submit the form</button> instead of <input type="submit">
ANOTHER EDIT:
I added simple select query and displayed the updated report on the page.
This is my idea about it:
user sends GET request - form is displayed
user sends POST request (submitting the form) - it is sent to itself, the from is displayed and the user gets feedback if update was successful, the udpated values being displayed
When creating something like this I always think on CRUD - create, retrieve, update, display.
The form should update an entry in the database.
For the retrieve part you should better use another view, displaying only the result, but not the form.
You could certainly send the form to the page where the result is displayed*, but I think that would be a bad practice. The user needs some feedback if the update action was successful.
for example something like this:
<form action="<?php echo 'previewgraphs?id=$id'; ?>">
You shouldn't squeeze to much logic into one part. Rethink your design. I'd also reccomend you to use a framework that implements the MVC pattern. You have a big choice. The framework will take care about many things and provide you also semantic URLs, so you'll have something like:
/reports
/reports/1
instead of appending all the parameters to the URL.
first restructure your code.
The first part of your code must save the values in case changes are being submitted. Then you read from the database again and show results.
However this could be a browser or proxy caching problem. I have a couple of tags that have been very helpful:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta http-equiv="cache-control" content="no-cache">
put them in the html < head > section . Older IEs do weird things with proxys sometimes.
Cheers, Karsten

calling data from database to make calculation (PHP)

I have problem, I want to calculate summation of height and weight after height is updated. The problem is after I click update, height is updated however weight will automatically change value to user_id (integer). So the summation will be bmi=height+id. Can you guys help solve my problem?
Below is PHP coding and form which I am using Bootstrap.
<!-- begin snippet: js hide: false -->
if(isset($_POST['updateH']))
{
$height = $_POST['height'];
$weight = $_SESSION['user'];
$bmi = $height + $weight;
$sql = "UPDATE users
SET
height = $height,
weight = $weight,
bmi = $bmi,
WHERE user_id=" . $_SESSION['user'];
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
}
else
echo mysql_error();
}
<form method="post" role="form">
<h3> Height : <?php echo $userRow['height']; ?> cm</h3>
<input type="number" class="small" name="height" id="height" min="100" max="200" placeholder="Update Height CM"/>
<button type="submit" class="btn btn-warning" name="updateH"> UPDATE </button>
</form>
It seems like a format error in your sql statement
Use this
$sql = "UPDATE users SET height ='".$height."',weight ='".$weight."',bmi ='".$bmi."' WHERE user_id='".$_SESSION['user']."'";
If it is not updated for the above query
call mysql_commit(); after your mysql_query(); statement
Let me know if it is helpful
You don't have input field for Weight.
May be you are noticing it or maybe I'm wrong
Ok try this html code
<form method="post" role="form">
<h3> Height : <?php echo $userRow['height']; ?> cm</h3>
<input type="number" class="small" name="height" id="height" min="100" max="200" placeholder="Update Height CM"/>
<input type="number" class="small" name="weight" id="height" min="10" max="200" placeholder="Update Weight CM"/>
<button type="submit" class="btn btn-warning" name="updateH"> UPDATE </button>
</form>
And in javascript use the following
if(isset($_POST['updateH']))
{
$height = $_POST['height'];
$weight = $_POST['weight'];
$bmi = $height + $weight;
$sql = "UPDATE users SET height ='".$height."',weight ='".$weight."',bmi ='".$bmi."' WHERE user_id='".$_SESSION['user']."'";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
}
else
echo mysql_error();
}

Failure to display result of a php script calculation in the textarea box

I believe that my problem may lie in the way that I am trying to initialize the script. The submit button that I am using seems to just clear the form, and not display any results. I also think there may be a problem with the two lines " $message = $_POST['textarea'];" and "echo $result + $message;" I am not sure if that is the correct way to produce a result into a text area box, as well as display the miles driven and total cost in their separate text boxes. I want this one button to do all three tasks. Is there a way to do this efficiently with PHP?
Edit: Corrected version of the code. Thank you #Fred-ii-!
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['textarea'];
echo $result + $message; }
?>
<html>
<head>
</script>
</head>
<body>
<div align="center">
<hr><br>
<form action="index4.php" method="post" name id="Main">
<input type="text" id="name" name="customerName" placeholder="Enter your name here" size="30px">
<br><br>
<input type="text" id="address" name="customerAddress" placeholder="Enter your street address here" size="50px">
<br><br>
<input type="text" id="city" name="customerCity" placeholder="What city do you live in?" size="30px">
<br><br>
<input type="number" id="zip" name="customerZip" placeholder="Enter your zip code" size="30px">
<br><br>
<input type="number" id="bOdometer" name="beginningOdometerReading" placeholder="Start odometer reading" size="80px">
<br><br>
<input type="number" id="eOdometer" name="endingOdometerReading" placeholder="End odometer reading" width="80px">
<br><br>
<input type="number" id="daysRented" name="daysRentedCar" placeholder="Days rented" size="50px">
<br><br>
<input type="submit" id="submit" value="Submit"/>
<br><br>
Miles Driven: <input type="number" id='miles' min="1" max"10000" readonly="" />
Total Cost: <input type="number" id='result' min="1" max"10000" readonly="" />
<br><br>
Summary: <textarea cols="30" rows="2" name="thetextarea" id="textarea"> </textarea>
<br><br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</body>
There are a few things wrong here.
One of the problems being with your conditional statement:
if(isset($_POST['submit'])) {
it is looking for a named element called "submit" which your submit button is not named.
<input type="submit" id="submit" value="Submit"/>
name it:
<input type="submit" name="submit" id="submit" value="Submit"/>
and you might have been relying on "id" for it. In this instance, you can't.
That is why you're getting back a blank page.
Having used an else{ echo "Error"; } would have echo'd "Error".
For example:
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['textarea'];
echo $result + $message; }
else { echo "Error"; }
?>
Then you have
$message = $_POST['textarea'];
but your textarea is named name="thetextarea".
Both of those need to match in names.
You are also using the wrong concatenate operator + for
echo $result + $message;
that needs to be a dot. The + sign is a JS/C++ method of concatenation, if one of those variables contains a string.
echo $result . $message;
or
echo $result . " ". $message;
Had it been a mathematical equation from two variables, then yes; that would have been a valid operator, just not in this case, since you are trying to echo from the $message variable, which is for the "textarea", being "text" and not an integer.
Sidenote: To ensure that you are indeed passing an integer to a POST array, add (int) to it. Example: $x = (int)$_POST['beginningOdometerReading'];
Edit: I found a few more errors in your form.
You have 2x instances of max"10000" it's missing an equal sign max="10000"
and you might be missing name attributes for both of these (which I already outlined are missing = signs for max"10000".
Miles Driven: <input type="number" id='miles' min="1" max"10000" readonly="" />
Total Cost: <input type="number" id='result' min="1" max"10000" readonly="" />
If you're relying on JS as you tagged this as, please edit your question and add that code. However, there was no code in your PHP to support this.
You've a syntax error in <form> being name id="Main"
You will need to adjust your actual code accordingly.
Rewrite:
<?php
if(isset($_POST['submit'])) {
$x = $_POST['beginningOdometerReading'];
$y = $_POST['endingOdometerReading'];
$z = $_POST['daysRentedCar'];
$miles = $y - $x;
$result = (15 * $z) + ($miles * 0.12);
$message = $_POST['thetextarea'];
echo $result . " " . $message; }
else { echo "Error"; }
?>
Error reporting would have signaled an undefined index notice for both of those.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Try to give name for input type `submit` button like
<input type="submit" name="submit" id="submit" value="Submit"/>
And try to remove from action='' because when you submit it directly takes to the index4.php and
error in form statement also you does not provide name you leave it empty like name id="Main"
<form action="index4.php" method="post" name="Main" id="Main">
And use echo statement like
echo $result,$message; }

Multiple forms onclick event only working for first form

I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}

Categories