Hi, I am a PHP developer I never learned much JS but there is no way to accomplish this function using only PHP without a refresh. I am trying to adapt a script that did the basics.

<script language="JavaScript">
function som()
{
  var First, Last, Full;
 
  First = document.Credit.First.value;
  Last  = document.Credit.Last.value;
  Full  = document.Credit.Full.value;
  document.Credit.Full.value = (First / Last);
}
</script>

My page is a dynamic php page using MySQL and I have created the JS using concatenation of strings in a loop for those items pulled from the DB table where sts==1 - this is really complicated to explain and this is my 2nd query on any forum and I only use daniweb. OK

Overall, if using the CMS the site owner selects certain items [sts==1] then I wrote the following to mark-up in PHP

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
	   if ($row['sts'] ==1){

		$jsvar .= " unit_price_". $row['pid'] .", " . "qty_" . $row['pid'] . ",";
		$jsunit .= "unit_price_". $row['pid'] ."=document.box.unit_price_". $row['pid'] .".value; ";
		$jsqty .= "qty_". $row['pid'] ." = document.box.qty_" . $row['pid'] .".value; ";
		$jstot .= "document.box.tot.value;";
		$jscalc .= " (unit_price_". $row['pid'] ." * qty_". $row['pid'] .") + ";
	   }
	} 

		$jsvar .=" tot;";
		$jscalc.= " 0;";
		$jscomplete = "<script language='JavaScript'>function sumtot() {". $jsvar . $jsunit . $jsqty . $jscalc ."}</script>";

This produces, in one instance the following:-

<script language='JavaScript'>
function sumtot() 
{
var  unit_price_8, qty_8, unit_price_9, qty_9, unit_price_10, qty_10, unit_price_12, qty_12, tot;
unit_price_8=document.box.unit_price_8.value; unit_price_9=document.box.unit_price_9.value; unit_price_10=document.box.unit_price_10.value; unit_price_12=document.box.unit_price_12.value; 
qty_8 = document.box.qty_8.value; qty_9 = document.box.qty_9.value; qty_10 = document.box.qty_10.value; qty_12 = document.box.qty_12.value; document.box.tot.value =  (unit_price_8 * qty_8) +  (unit_price_9 * qty_9) +  (unit_price_10 * qty_10) +  (unit_price_12 * qty_12) +  0;}</script>

This is dynamic creation of JS code always ends up with the calclation equalling zero.

IF ANYONE CAN FOLLOW THIS AND ANSWER WITH AN ANSWER THAT WORKS I WILL BE MORE THAN HAPPY TO USE YOU AS A CONTRACTOR...

The whole code for the PHP on this page is -

<?php
session_start();
require_once ('../mysql_connect.php'); // Connect to the db.

$cid = $_POST['cid'];
$surname = $_POST['surname'];
$order = $_POST['order'];


/* Retrieve the cid and surname for that combination. */
		$query = "SELECT * FROM customer WHERE cid='$cid' AND surname='$surname'";		
		$result = @mysql_query ($query); // Run the query.
		$row = mysql_fetch_array ($result, MYSQL_NUM); // Return a record, if applicable.



/* ============ ALL OK WITH LOGON ================ */

		if ($row) { // A record was pulled from the database.

			// Set the session data & redirect.
			session_name ('YourVisitID');
			session_start();
			$_SESSION['cid'] = $row[0];
			$_SESSION['surname'] = $row[3];
			$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);

/* ============= LOG DETAILS ============= */

$title = $row[2];
$surname = $row[3];
$add1 = $row[4];
$add2 = $row[5];
$add3 = $row[6];
$add4 = $row[7];
$pc = $row[8];
$round = $row[19];
$email = $row[9];

/* =============== CREATE JS =============== */

	$query  = "SELECT * FROM product";
	$result = mysql_query($query);

$jsvar = "var ";
$jsunit = "";
$jsqty = "";
$jstot = "";
$jscalc = "document.box.tot.value = ";

	while($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
	   if ($row['sts'] ==1){

		$jsvar .= " unit_price_". $row['pid'] .", " . "qty_" . $row['pid'] . ",";
		$jsunit .= "unit_price_". $row['pid'] ."=document.box.unit_price_". $row['pid'] .".value; ";
		$jsqty .= "qty_". $row['pid'] ." = document.box.qty_" . $row['pid'] .".value; ";
		$jstot .= "document.box.tot.value;";
		$jscalc .= " (unit_price_". $row['pid'] ." * qty_". $row['pid'] .") + ";
	   }
	} 

		$jsvar .=" tot;";
		$jscalc.= " 0;";
		$jscomplete = "<script language='JavaScript'>function sumtot() {". $jsvar . $jsunit . $jsqty . $jscalc ."}</script>";






/* ============== LIST DETAILS ============ */

echo '
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="http://www.slipstream-organics.co.uk/css.css" />
<meta name="author" content="Andrew Frazer" />
<meta name="description" content="" />
<meta name="keywords" content="" />	';

echo $jscomplete;

echo '
</head>
<body>
<img src="../images/logo.gif" width="400" height="47">
';
?>
<script language="JavaScript">
document.write('IS THIS PRINTING');
document.write(unit_price_8);
</script>

<?php

echo"
	<table style='width:400px;'>
	 <tr>
		<td colspan='2' style='color:#363;font-weight:bold;text-align:left;line-height:1.5em;font-family:verdana, helvetics, sans-serif;'>Your Details</td>
	 </tr>
	</table>
	<table style='width:400px;background:rgb(230,240,230);'>
	 <tr>
		<td><p class='header'>Name: </p></td><td><p class='header'>" . $title . " " . $surname. "</p></td>
	 </tr>
		<td style='vertical-align:top;'><p class='header'><p class='header'>Address: </p></td>
		<td><p class='header'>" . $add1 . "&nbsp;" . $add2 . "<br />" . $add3 . "<br />" . $add4 . "<br />" . $pc . "</p></td>
	 </tr>";

	if ($email) {

		echo "
	 <tr><td><p class='header'>Email: </td><td><p class='header'>" . $email . "</p></td></tr>";

	}

echo"	 <tr>
		<td><p class='header'>Delivery Round: </p></td><td><p class='header'>" . $round . "</p></td></tr></table>";

echo "<br />";

	if ($order == "replace"){

		echo "<p class='header' style='color:#800;'>THIS ORDER WILL <b>REPLACE</b> YOUR ORDER <b>THIS</b> WEEK</p>";

	} else {

		echo "<p class='header' style='color:#800;'>THIS ORDER WILL <b>BE ADDED</b> YOUR ORDER <b>THIS</b> WEEK</p>";
	}


echo "<p>Some text here to explain what to do, Nick...</p>";

echo "<form method='POST' name='box' action='order.php'><table style='color:#363;font-size:85%;font-family:verdana, helvetica, sans-serif;'>
       <tr>
	  <td><b>Product</b></td>
	  <td style='width:50px;text-align:left;'><b>Unit</b></td>
	  <td style='text-align:right;'><b>Price</b></td>
	  <td><b>Qty</b></td>
	  <td><b>Line Total</b></td>
	 </tr>";

/* Retrieve the data for form. */
	$query  = "SELECT * FROM product";
	$result = mysql_query($query);

$jsvar = "var ";
$jsunit = "";
$jsqty = "";
$jstot = "";
$jscalc = "document.box.tot.value = ";

	while($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
	   if ($row['sts'] ==1){

		echo "<tr>
				<td>" . $row['product_description'] . "</td>
				<td>" . $row['unit'] . "</td>
				<td>&pound;" . $row['unit_price'] . "</td><input type='hidden' name='unit_price_". $row['pid'] ."' />
				<td><input type='text' size='4' name='qty_" . $row['pid'] . "' /><td>
				<td>ln tot</td>
			</tr>";

$jsvar .= " unit_price_". $row['pid'] .", " . "qty_" . $row['pid'] . ",";
$jsunit .= "unit_price_". $row['pid'] ."=document.box.unit_price_". $row['pid'] .".value; ";
$jsqty .= "qty_". $row['pid'] ." = document.box.qty_" . $row['pid'] .".value; ";
$jstot .= "document.box.tot.value;";
$jscalc .= " (unit_price_". $row['pid'] ." * qty_". $row['pid'] .") + ";
	   }
	} 

$jsvar .=" tot;";
$jscalc.= " 0;";
// echo $jsvar;
// echo $jsunit;
// echo $jsqty;
// echo $jscalc;

	   echo "</table><input type='submit' value='Send Order' />";
	   echo "<input name='tot' type='text' /><input type='button' value='Calculate' onClick='sumtot()'></form>";

?>
<script language="JavaScript">
document.write('IS THIS PRINTING');
document.write(unit_price_8);
document.write(qty_8);
</script>
 
<?php


/*  ============== LOGON FAILED ============= */
		} else {

		echo "Sorry your details do not match those on our records.<br />Click <a href='http://www.slipstream-organics.co.uk/makeyourownbox/index.php'>here</a> to go back.";
		}				
	mysql_close(); // Close the database connection.
?>

</body>
</html>

Aventurine,

At least part of the problem is that the hidden unit_price fields don't have values. That needs to be fixed.

But we can go much further to avoid unnecessary complexity in building the page, plus a go-faster goodie.

The JavaScript function sumtot can be hard-coded as follows :

onload = function() {
	var products = document.getElementById('products');
	
	function getPID(id) {//utility function
		return id.split('_')[1];//extract n from "pid_n"
	}

	function sumtot() {
		var tot = 0;
		for(var i=0; i<products.rows.length; i++) {
			var pid = getPID(products.rows[i].id);
			var unit_price = Number(document.box['unit_price_'+pid].value);
			var qty = Number(document.box['qty_'+pid].value);
			var ln_tot = unit_price * qty;
			if(!isNaN(ln_tot)) {
				var line_total_cell = document.getElementById('ln_tot_'+pid);
				if(line_total_cell) { line_total_cell.innerHTML = "&pound;" + ln_tot.toFixed(2); }
				if(tot !== false) { tot += ln_tot; }
			}
			else {
				document.getElementById('ln_tot_'+pid).innerHTML = "error";
				tot = false;
			}
		}
		var totPrint = (tot === false) ? 'error' : tot.toFixed(2);
		document.box.tot.value = totPrint;// tot
		document.getElementById('tot2').innerHTML = totPrint; // tot2
	}
	
	//Here we give eqach of the qty fields an event handler for automatic, spreadsheet-like calculation
	for(var i=0; i<products.rows.length; i++) {
		var pid = getPID(products.rows[i].id);
		var qtyField = document.box['qty_'+pid];
		if(qtyField) { qtyField.onkeyup = qtyField.onblur = sumtot; }
	}
	document.getElementById('calcButton').onclick = sumtot;

	sumtot();//This ensures that initial products and total are shown (eg. zeros all through)
};

And the corresponding HTML is:

<form method='POST' name='box' action='order.php'>
<table style="color:#363;font-size:85%;font-family:verdana, helvetica, sans-serif;" border>

<tr>
<th>Product</th>
<th style="width:50px;text-align:left;">Unit</th>
<th style="text-align:right;">Price</th>
<th>Qty</th>
<th>Line Total</th>
</tr>

<tbody id="products"><!-- This is critical -->

<tr id="pid_8"><!-- Give each row an id reflecting its pid -->
<td>product_description 8</td>
<td>unit</td>
<td>&pound;1.50</td><input type="hidden" name="unit_price_8" value="1.5" />
<td><input type="text" size="4" name="qty_8" value="0" style="text-align:center;" /></td>
<td id="ln_tot_8" align="center"></td>
</tr>

<tr id="pid_9">
<td>product_description 9</td>
<td>unit</td>
<td>&pound;2.50</td><input type="hidden" name="unit_price_9" value="2.5" />
<td><input type="text" size="4" name="qty_9" value="0" style="text-align:center;" /></td>
<td id="ln_tot_9" align="center"></td>
</tr>

<tr id="pid_12">
<td>product_description 12</td>
<td>unit</td>
<td>&pound;3.00</td><input type="hidden" name="unit_price_12" value="3.0" />
<td><input type="text" size="4" name="qty_12" value="0" style="text-align:center;" /></td>
<td id="ln_tot_12" align="center"></td>
</tr>

</tbody>

</table>
Total &pound;&nbsp;<input name="tot" type="text" disabled />&nbsp;Total &pound;<span id="tot2"></span>
<br /><br />
<input id="calcButton" type="button" value="Calculate" onClick="sumtot()" />
</form>

You will be much quicker than I in modifying the php to build out the table in that way.

I have included onblur and onkeyup event handlers for the qty fields, which makes the "CALCULATE" button pretty well redundant (at least in the major browsers), however don't delete it as there may be some browser somewhere that doesn't see the other event types.

You might consider making the tot container a <span> unless you feel it should be submitted as part of the form. I have included a tot2 element to demonstrate how to do this. Either tot or tot2 can be deleted (along with the corresponding line of code in sumtot )

Airshow

You are currently have the following (on line 164):

<input type='hidden' name='unit_price_". $row['pid'] ."' />

The js function needs to compute: unit_price_X * qty_X (where X is whatever value is in $row['pid'] )
but you have NOT assigned a value! Since it is a hidden field, the user cannot enter anything either. You MUST assign it a value.

try:

<?php
session_start();
require_once ('../mysql_connect.php'); // Connect to the db.

$cid = mysql_real_escape_string($_POST['cid']);
$surname = mysql_real_escape_string($_POST['surname']);
$order = mysql_real_escape_string($_POST['order']);


/* Retrieve the cid and surname for that combination. */
$query = "SELECT * FROM customer WHERE cid='$cid' AND surname='$surname'";	

// Run the query.
$result = @mysql_query ($query); 

// Return a record, if applicable.
$row = mysql_fetch_array ($result, MYSQL_NUM); 



/* ============ ALL OK WITH LOGON ================ */
// A record was pulled from the database.
if ($row)
{ 

	// Set the session data & redirect.
	session_name ('YourVisitID');
	session_start();
	$_SESSION['cid'] = $row[0];
	$_SESSION['surname'] = $row[3];
	$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);

	/* ============= LOG DETAILS ============= */
	$title = $row[2];
	$surname = $row[3];
	$add1 = $row[4];
	$add2 = $row[5];
	$add3 = $row[6];
	$add4 = $row[7];
	$pc = $row[8];
	$round = $row[19];
	$email = $row[9];

	/* =============== CREATE JS =============== */
	$query  = "SELECT * FROM product";
	$result = mysql_query($query);

	$jsvar = "var ";
	$jsunit = "";
	$jsqty = "";
	$jstot = "";
	$jscalc = "document.box.tot.value = ";

	while($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
	   if ($row['sts'] ==1){

		$jsvar .= " unit_price_". $row['pid'] .", " . "qty_" . $row['pid'] . ",";
		$jsunit .= "unit_price_". $row['pid'] ."=document.box.unit_price_". $row['pid'] .".value;\n";
		$jsqty .= "qty_". $row['pid'] ." = document.box.qty_" . $row['pid'] .".value;\n";
		$jscalc .= " (unit_price_". $row['pid'] ." * qty_". $row['pid'] .") + ";
	   }
	} 

	$jsvar .=" tot;\n";
	$jscalc.= " 0;";
	$jscomplete = "<script type='text/javascript'>function sumtot() {\n". $jsvar . $jsunit . $jsqty . $jscalc ."\n}\n</script>";

	/* ============== LIST DETAILS ============ */

	echo '
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="http://www.slipstream-organics.co.uk/css.css" />
<meta name="author" content="Andrew Frazer" />
<meta name="description" content="" />
<meta name="keywords" content="" />	';

echo $jscomplete;

echo '
</head>
<body>
<img src="../images/logo.gif" width="400" height="47">
';

echo"
	<table style='width:400px;'>
	 <tr>
		<td colspan='2' style='color:#363;font-weight:bold;text-align:left;line-height:1.5em;font-family:verdana, helvetics, sans-serif;'>Your Details</td>
	 </tr>
	</table>
	<table style='width:400px;background:rgb(230,240,230);'>
	 <tr>
		<td><p class='header'>Name: </p></td><td><p class='header'>" . $title . " " . $surname. "</p></td>
	 </tr>
		<td style='vertical-align:top;'><p class='header'><p class='header'>Address: </p></td>
		<td><p class='header'>" . $add1 . "&nbsp;" . $add2 . "<br />" . $add3 . "<br />" . $add4 . "<br />" . $pc . "</p></td>
	 </tr>";

	if ($email) {

		echo "
	 <tr><td><p class='header'>Email: </td><td><p class='header'>" . $email . "</p></td></tr>";

	}

	echo"	 <tr>
		<td><p class='header'>Delivery Round: </p></td><td><p class='header'>" . $round . "</p></td></tr></table>";

	echo "<br />";

	if ($order == "replace"){

		echo "<p class='header' style='color:#800;'>THIS ORDER WILL <b>REPLACE</b> YOUR ORDER <b>THIS</b> WEEK</p>";

	} else {

		echo "<p class='header' style='color:#800;'>THIS ORDER WILL <b>BE ADDED</b> YOUR ORDER <b>THIS</b> WEEK</p>";
	}


	echo "<p>Some text here to explain what to do, Nick...</p>";

	echo "<form method='POST' id='box' name='box' action='order.php'><table style='color:#363;font-size:85%;font-family:verdana, helvetica, sans-serif;'>
       <tr>
	  <td><b>Product</b></td>
	  <td style='width:50px;text-align:left;'><b>Unit</b></td>
	  <td style='text-align:right;'><b>Price</b></td>
	  <td><b>Qty</b></td>
	  <td><b>Line Total</b></td>
	 </tr>";

	 /* Retrieve the data for form. */
	$query  = "SELECT * FROM product";
	$result = mysql_query($query);

	$jsvar = "var ";
	$jsunit = "";
	$jsqty = "";
	$jstot = "";
	$jscalc = "document.box.tot.value = ";

	while($row = mysql_fetch_assoc($result))
	{
		if ($row['sts'] ==1){

			echo "<tr>
					<td>" . $row['product_description'] . "</td>
					<td>" . $row['unit'] . "</td>
					<td>&pound;" . $row['unit_price'] . "</td><input type='hidden' name='unit_price_". $row['pid'] ."' value='".$row['unit_price']."'/>
					<td><input type='text' size='4' name='qty_" . $row['pid'] . "' /><td>
					<td>ln tot</td>
				</tr>";

			$jsvar  .= " unit_price_". $row['pid'] .", " . "qty_" . $row['pid'] . ",";
			$jsunit .= " unit_price_". $row['pid'] ."=document.box.unit_price_". $row['pid'] .".value;\n";
			$jsqty  .= " qty_". $row['pid'] ." = document.box.qty_" . $row['pid'] .".value;\n";
			$jscalc .= " (unit_price_". $row['pid'] ." * qty_". $row['pid'] .") + ";
	   }
	}

	$jsvar .=" tot;\n";
	$jscalc.= " 0;\n";

	// echo $jsvar;
	// echo $jsunit;
	// echo $jsqty;
	// echo $jscalc;

	echo "</table><input type='submit' value='Send Order' />";
	echo "<input name='tot' type='text' /><input type='button' value='Calculate' onClick='sumtot()'></form>";
?>
<script type="text/javascript">
document.write('IS THIS PRINTING');
document.write(document.box.unit_price_8.value);
document.write(document.box.qty_8.value);
</script>
 
<?php


/*  ============== LOGON FAILED ============= */
		} else {

		echo "Sorry your details do not match those on our records.<br />Click <a href='http://www.slipstream-organics.co.uk/makeyourownbox/index.php'>here</a> to go back.";
		}				
	mysql_close(); // Close the database connection.
?>

</body>
</html>

Apologies Airshow. Your post was not yet there when I opened the page.

Regards,
Hielo

No worries Hielo.

A

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.