trying to pass JS to PHP

12Strings

Junior Member
Dec 16, 2014
4
0
0
HI, I'm worrying with a calendar, trying to send to & print out
a list of entries. I must not be doing the "OnCalc " function right
(in the Html or Php)?
Doing an alert of the values in this following presents the right
values but no results. Any help?
--------------------
HTML:
<input name="btnEquals" type="Button" value="   =   " onclick="Operation('=')"></TD> 
</TR></TABLE>
 <INPUT type="image" src="programmer.gif" alt="submit button"><p>
</FORM> 
<font face="Verdana, Arial, Helvetica" size=2> 
<SCRIPT LANGUAGE="JavaScript"> 
var FKeyPad = document.Keypad; 
var purpose = 0;
var Accumulate = 0; 
var FlagNewNum = false; 
var PendingOp = ""; 
function NumPressed (Num) 
{ 
if (FlagNewNum) 
{ FKeyPad.ReadOut.value = Num; 
FlagNewNum = false; 
} 
else 
{ 
if (FKeyPad.ReadOut.value == "0") 
FKeyPad.ReadOut.value = Num;

else 
FKeyPad.ReadOut.value += Num; 
} 
} 
function Operation (Op) 
{ 
var Readout = FKeyPad.ReadOut.value; 
if (FlagNewNum && PendingOp != "="); 
else 
{ 
FlagNewNum = true; 
if ( '+' == PendingOp )
{ 
var temp = Accumulate;
Accumulate += parseFloat(Readout); 
OnCalc(temp,PendingOp,Readout,Accumulate);
}
else if ( '-' == PendingOp ) 
{
var temp = Accumulate;
Accumulate -= parseFloat(Readout); 
OnCalc(temp,PendingOp,Readout,Accumulate);
}
else if ( '/' == PendingOp ) 
{
var temp = Accumulate;
Accumulate /= parseFloat(Readout); 
OnCalc(temp,PendingOp,Readout,Accumulate);
}
else if ( '*' == PendingOp ) 
{
var temp = Accumulate;
Accumulate *= parseFloat(Readout); 
OnCalc(temp,PendingOp,Readout,Accumulate);
}
else 
{
Accumulate = parseFloat(Readout); 
}
FKeyPad.ReadOut.value = Accumulate; 

PendingOp = Op; 
} 
} 
function Decimal () 
{ 
var curReadOut = FKeyPad.ReadOut.value; 
if (FlagNewNum) 
{ 
curReadOut = "0."; 
FlagNewNum = false; 
} 
else 
{ 
if
(curReadOut.indexOf(".") == -1) 
curReadOut += "."; 
} 
FKeyPad.ReadOut.value = curReadOut; 
} 
function ClearEntry () 
{ 
FKeyPad.ReadOut.value = "0"; 
FlagNewNum = true; 
} 
function Clear () 
{ 
Accumulate = 0; 
PendingOp = ""; 
ClearEntry(); 
} 
function Neg () 
{ 
FKeyPad.ReadOut.value = parseFloat(FKeyPad.ReadOut.value) * -1; 
} 
function Percent () 
{ 
FKeyPad.ReadOut.value = (parseFloat(FKeyPad.ReadOut.value) / 100) * 
parseFloat(Accumulate); 
 }
if (value1 == parseInt(num))
 {value1.value = parseInt(value1.value)}
else
 {value1.value = parsefloat(value1.value)}

if (value2 == parseInt(num))
 {value2.value = parseInt(value2.value)}
else
 {value2.value = parsefloat(value2.value)}

if (total == parseInt(num))
 {total.value = parseInt(total.value)}
else
 {total.value = parsefloat(total.value)}

<!-- use ajax - OnCalc function to send data to your database. --> 
function OnCalc(value1,op,value2,total)
alert(value1);
 {
var expression = value1 + op +value2 +'='+ total;
alert(expression); 
 }
</SCRIPT>
</body></html>
-------------------------------------------

PHP:
<?php
  header( "refresh:5;url='http://localhost/home/calcprint.php'");
  echo 'You\'ll be redirected in about 5 secs. If not, click <a href="http://localhost/home/calcprint.php">here</a>.'; 

include ('gethomedb.php');
// now connected to database
    if(!empty($_POST["submit"])) 
 {
echo '<script type="text/javascript">'
   , 'OnCalc();'
   , '</script>';

       $id = $_POST['id'];
 $purpose=$_POST['purpose'];
 $value1=$_POST['value1'];
         $op=$_POST['op'];
 $value2=$_POST['value2'];
   $total=$_POST['total'];
  $name = $_POST['id'];
 if(isset($_POST['id']))  
 {       
   $fetch="SELECT * FROM calculator";    
       $result = mysqli_query($con,$fetch);  
        if(!$result)  
         {echo "Error:".(mysqli_error($con));}
// ===========================================================   
$query = "
INSERT INTO calculator (purpose, value1, op, value2, total)
VALUES ('$purpose','$value1','$op','$value2','$total')";
mysqli_query($con, $query);
mysqli_close($con); 
 }
  }
?>
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,645
4,588
75
See where it says "use ajax"? Maybe you should use AJAX. ;)

OK, this probably needs more work than that. I would suggest one PHP page to display the calculator (not a calendar), and another to handle AJAX requests. You may also want to do some DOM manipulation, of at least the result field.

Also, your SQL is very insecure. Which is probably acceptable if you don't put this on the public Internet.
 

mrjminer

Platinum Member
Dec 2, 2005
2,739
16
76
I didn't look at your JS, but your SQL is not acceptable in any circumstance. You need to sanitize your input with mysqli_real_escape_string.

Additionally, you fail to check for the presence of the values in the input and perform any validation on them, and have no nonce (which will subject you to CSRF attacks).

I haven't coded any PHP in like a year and this in untested, but it should point you in the right direction. I didn't add any nonce to the below, either.

Code:
 <?php
  header( "refresh:5;url='http://localhost/home/calcprint.php'");
  echo 'You\'ll be redirected in about 5 secs. If not, click <a href="[URL="http://localhost/home/calcprint.php&quot;>here</a>.'"]http://localhost/home/calcprint.php">here</a>.'[/URL]; 
 include ('gethomedb.php');
// now connected to database
if(!empty($_POST["submit"])) 
{
 echo '<script type="text/javascript">OnCalc();</script>';
 
 // Note your original example had the $name equal to the same value as the 'id', then never use it.  So, I omitted it here entirely, though you may have meant to assign it to the 'id'.  Your original also doesn't use the value of the 'id', either, though.
 // If the ID isn't actually required, you can remove it from the following.
 // Also note that you should be generating a nonce/security token and checking it as a field, too.
 foreach(array('id', 'purpose', 'value1', 'op', 'value2', 'total') as $k => &$v) {
  if(isset($_POST[$v]) !== true) {
   die('Missing required value for index:  ' . $v);
  }
  if(is_string($_POST[$v]) !== true) {
   die('Invalid data type for the of index:  ' . $v);
  }
  // Note:  this trim is optional and depends on whether you want left/right whitespace from the user entry field to be removed.  Typically, this is the case for text inputs.  However, if using something like a SELECT / OPTION where the user should not manipulate the data, you may want to omit this in the loop and run it only on specific variables for which the user has direct entry.
  $temp[$v] = trim($_POST[$v]);
 }
 
 // Now, validate the values submitted accordingly
 $id = $temp['id'];
 if(ctype_digit($id) !== true)
 {
  // Of course, this assumes the "id" is supposed to be only digits.
  die('Invalid value submitted for the index:  id');
 }
 // Cast the ID to an integer (which will not need to be validated with mysqli_real_escape_string since it is not a string, and a digit cannot result in a malicious DB operation occurring.  In other words, a digit can't contain a character that can result in manipulation of your expected SQL query, such as an apostrophe or quotation.)
 $id = (int)$id;
 
 // Assuming the following are allowed to be decimals
 foreach(array('value1', 'value2', 'total') as $k => &$v) {
  // Split on potential decimal point
  $temp2 = preg_split('\.', $temp[$v], 2);
  
  // One value will always be present.
  if($temp2[0] === '') {
    // Nothing was entered or nothing was entered to the left of the decimal.  You could assume '0' here, or throw an error if the user must enter something.
    $temp[$v] = 0;
   } elseif(ctype_digit($temp2[0]) !== true) {
    // A value was entered.  Since there are no decimals, it must be an integer.
    die('Invalid value submitted for the index:  ' $v);
   } else {
    // The value was an integer; cast it to an integer here.
    $temp[$v] = (int)$temp[$v];
   }
  }
  
  // Note the below processing could be optimized, of course, but should suffice for this example.
  if(count($temp2) === 2) {
   // A split occurred.  The previous assignment was for the left side of the decimal.  Now, the right side must be checked.
   if($temp2[1] === '') {
    // Nothing was entered after the decimal; you could omit this if you don't want a ".0" at the end.
    $temp[$v] = $temp[$v] . '.0';
   } elseif(ctype_digit($temp2[1]) !== true) {
    // The value to the right should be an integer, as well, but contains characters other than integers.
    die('Invalid value submitted for the index:  ' $v);
   } else {
    // The value to the right was an integer; cast it to an integer here, and add the left side back.
    $temp[$v] = $temp[$v] . '.' (int)$temp2[1];
   }
  }
 }
 
 // Now, $id, $value1, $value2, and $total are sanitized and do not need to be escaped in a query.  The ones I assume are strings, still need to be, though.  We will assign it here so we can more easily construct the query using an implode() on the array of values, rather than annoyingly typing out ',' . $blah . ',' . $blah2 . etc.
 $temp['purpose'] = mysqli_real_escape_string($con, $temp['purpose']);
 $temp['op'] = mysqli_real_escape_string($con, $temp['op']);
 
 // NOTE:  This seems pretty out-of-order, but I'm not sure what you're doing since I'm too lazy to look at your JS.  If you ONLY want to perform some sort of operation if the ID is present, you should check it independently before anything else, then only proceed with checking the other values if the ID is present, for optimization purposes.
    if(isset($_POST['id']))  
 {
  // Pretty non-optimal to select everything from the calculator table.  If the table is large, this will be slow.
  $fetch="SELECT * FROM calculator";    
  $result = mysqli_query($con,$fetch);
  // You should use mysqli_fetch_assoc or something here, and perhaps actually do something with the result.  Effectively, you are just getting all of the data from the calculator table, then doing nothing with it at all other than seeing if you got a result back.  You could omit this entirely and perform this test on the INSERT query (which I suspect is what you actually intend).
   if(!$result)  
    {echo "Error:".(mysqli_error($con));}
    
  // Implode magic here.  Also, note, if you aren't actually inserting the ID they provided, do : "unset($temp['id']);" prior to this, and remove the id from the list of fields you will be inserting below.
 //unset($temp['id']);
  $query = '
   INSERT INTO calculator (id, purpose, value1, op, value2, total)
   VALUES (' . implode("','", $temp) . ')';
   
  // You also need to check if an error occurred when executing the query.
  mysqli_query($con, $query);
  mysqli_close($con); 
 }
}
?>
 
Last edited:

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,645
4,588
75
Probably true. At the time I thought he had enough other problems with this homework problem. But it is good to develop good habits.
 

mrjminer

Platinum Member
Dec 2, 2005
2,739
16
76
Probably true. At the time I thought he had enough other problems with this homework problem. But it is good to develop good habits.

Yea, it is riddled with problems. Hopefully he will understand.
 

12Strings

Junior Member
Dec 16, 2014
4
0
0
this is a localhost project
I key in the calculaor values "purpose", "value1", "op", "value2" & "total".
1)the user(me) is given the option YES and NO of refreshing the database and The options SuBMIT and PRINT.
2)option YES refeshes the database
3)submitting NO inserts the record into database and returns to the calculator for another entry.
4)clicking PRINT prints the report
Being relatively inexperienced(inept), I don't know how to get the 4 variables to the php. I do know I don't need ajax. I don't get errors but also no insert. The problem is that I don't know how
to forward the variables. I've been referred to dozens of relative sites. trying not to be verbose, I'm trimming the code.
HTML:
<form name="Keypad" action="http://localhost/home/PHPinsert.php" method="post">
<input type="text" size = 50 STYLE="color: #000000; background-color: #ccffff;" name="purpose" value="what's this for?" onFocus="this.value=''"><br>

<TD colspan=3> </TD> 
<TD><input name="btnEquals" type="Button" value="    =    " 
onclick="Operation('=')"></TD> 
</TR> </TABLE> 
<input type="submit" name="keypad" value="submit">
</FORM> <font face="Verdana, Arial, Helvetica" size=2>
 
<SCRIPT> 

}
/* ****************************************************** 
function OnCalc(value1,op,value2,total)
{return(value1,op,value2,total);}
/* ******************************************************
</SCRIPT> 

<a href="http://localhost/home/calcprint.php">print</a>
</center></b></font></body></html>
----------------------------------------------
PHP:
<?php
  include ('gethomedb.php');
  // now connected to database  
        if(!empty($_POST["submit"])) 
 {
   $purpose=$_POST['purpose'];
     $value1=$_POST['value1'];
             $op=$_POST['op'];
     $value2=$_POST['value2'];
       $total=$_POST['total'];
           
    $fetch="SELECT * FROM calculator";    
        $result = mysqli_query($con,$fetch);  
         if(!$result)  
          {echo "Error:".(mysqli_error($con));}
 // ===========================================================   
 $query = "
 INSERT INTO calculator (purpose, value1, op, value2, total)
 VALUES ('$purpose','$value1','$op','$value2','$total')";
 mysqli_query($con, $query);
 mysqli_close($con); 
}
/* Redirect browser */
header("Location: http://localhost/home/PHPinsert.html"); 
exit;
?>
 

Sgraffite

Member
Jul 4, 2001
188
125
116
Being relatively inexperienced(inept), I don't know how to get the 4 variables to the php. I do know I don't need ajax. I don't get errors but also no insert. The problem is that I don't know how
to forward the variables.

Your form contains 3 inputs: text, btnEquals, and submit.

You are looking for these 5 variables from the POST on the serve side:
Code:
$purpose=$_POST['purpose'];
$value1=$_POST['value1'];
$op=$_POST['op'];
$value2=$_POST['value2'];
$total=$_POST['total'];

So you are posting 3 values, and then looking for 5 completely different values on the server side. You can create input elements for the data that you want to post, and use javascript to set the value of those elements prior to posting the data.

Also your SQL is broken in the same manner it was in December.