using functions

Hi, I could use a little guidance here. 1) is a function with
values to be sent to 2).

1) <!-- use ajax - OnCalc function to send data to your database. --> 
function OnCalc(value1,op,value2,total)
  {
  1. php file using above function values
    [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.’;

echo ‘’;[/php]
No error but code not working?

Hmmmm, where to start…

First, you show us a function which is Javascript…

Next, you show us a PHP script which takes you to another page and then prints out a Javascript routine.

When testing small code scripts like this, is it best to place all of the code on one page and test. Then, if
it does not work, you can post the entire page which would be only a few lines long and we could see how
all of the parts fit together. But, here is what I see so far…

You must remember that when using PHP is it SERVER-SIDE ONLY. What this means is that it runs on the
server first. All output of the HTML and PRINTED output from the PHP is sent out to the browser. This is
(browser) is CLIENT-SIDE along with JS code which is handled CLIENT-SIDE in the browser. What all of this
means is that you will never see any PHP code if you VIEW-SOURCE of your site’s page.

So, in your PHP code, the first line tells it to go to another page. This means that it will not allow anything
to be run after it. Perhaps you are doing that to keep the page refreshed. There is no reason in the world
that I can think of for doing that. Why wait for a user to click within five seconds? Just take them to the
page.

And, you set up a function to pull in four variables. That is, four JS variables. NOT PHP ones. So, if you
redirect the page in 5 seconds, the JS variables on the page are completely reset to nulls when the page
is loaded. Therefore, there will never be anything in the variables. Also, when you call this function, you
are not sending the variables, just null. So, to call the function, you need to pass it some data.
Such as: OnCalc(“99”, “+”, “999”, total); NOT OnCalc(); Can’t calculate nothing…

Now, since you only have 5 seconds to enter your inputs, this most likely would never work. So, hope this
helps you somewhat. Not really sure what you are attempting to do. Perhaps a little more info on your
project would be helpful. Is this a school project? Here is a site that explains most ALL programming needs
in very simple tutorials and may help you further. You can view various topic on the left and walk thru the
tutorials using the next page buttons at the end of each example. Very good site!
Good luck. http://www.w3schools.com/js/js_functions.asp

Hey good peoples, got your Christmas shopping done? Me either.
I’ve got this calculator code, I want to enter calculator results
into a database and when desired print out the report with the total
as in a calculator tape. I enter the record but when I enter “submit”
I get the following message:

js_var is not set! Print

I’m trying to learn and use ajax to pass the JS code to my PHP. I may be totally misunderstanding this whole concept. This after much study re. this issue. This is my pastime, hopefully forestalling memory issues.At an rate, following is my code. Help?

[code]<!doctype HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>

calculator insert input{ text-align:center; }
<input name="btnPlus" type="Button" value=" + "

onclick=“Operation(’+’)”>

<input name="btnMinus" type="Button" value=" - "

onclick=“Operation(’-’)”>

<input name="btnThree" type="Button" value=" 3 " onclick="NumPressed <p>(3)"></p> </TD> <TD></TD> <TD align=middle><input name="btnMultiply" type="Button" value=" * "

onclick=“Operation(’*’)”>

<input name="btnDivide" type="Button" value=" / "

onclick=“Operation(’/’)”>

[/code]

calc.php:

<?php?> [php]<?php include ('gethomedb.php'); // now connected to database

if (isset($_GET[‘js_var’])) $php_var = $_GET[‘js_var’];
else $php_var = “
js_var is not set!”;
echo $php_var;

if(!empty($_POST["submit"])) 

{
echo ‘’;

    $id = $_POST['id'];

$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);
}
?>[/php]

[code]Print

[/code]

Merry Christmas to you, too… Even if you are not in an area that celebrates it…

Anyways, I think you do not understand the Javacript vs PHP issue clearly…

First, PHP is server-side only. Javascript is client-side only. PHP sends pages to the client side
and Javascript NOT something that can send to server-side. Now, you CAN use JS to call a AJAX
script to load a PHP file into the currently viewed page. This is totally NOT secure as anyone who
can view your page can see the codes used to call the PHP page and can therefore alter them to load
what they want from your PHP file… So, this is NOT a secure way to set up a site.

So, first, you said you wanted to create a calculator type of page. This can be done easy with just
HTML and Javascript. I can post code for that. But, then, you asked to use AJAX to load info to pass
the output of the JS to a database. THIS IS NOT the way to go ! ! ! ! ! It is so totally the way to handle
this process. Totally 100% insecure!

Now that I have ranted on how this is wrong… Javascript as I said in my last post, is CLIENT-SIDE. This
means that it is handled inside the browser. This also means that it can alter posted values that the
user puts insides fields. So therefore, a safe way and very more secure way would be to use the JS to
alter the field values and then just post the page. In this manner, the “form” would just post back to the
PHP page which would use standard form validations and database updates to save the data from the
form fields. It does NOT make sense to use AJAX in this type of project. Mostly due to not being secure.
The data in your database would be wide open to any beginner hacker.

Hope that add to the previous post. Perhaps you should just create a working calculator page just in HTML and JS to handle your calculations first. Then, put the outputs of the calculations into “HIDDEN” fields in the
form’s input fields and then just post the page. This would then send it to the php code that can update the
database as needed. No need for any type of AJAX which really is not secured since it can be viewed by the
use… (Just RIGHT-CLICK on any ( YES, ANY ! ! ! ! ! ! ) website in the world and you can see THEIR Javascript
that they used on their page… )

Not sure if this helps , but, hope so…

While you present some good points your entire rant about Ajax not being secure is totally missing the mark.

Ajax doesn’t need to be secure. Ajax does not give a user “direct access” to a database. That the code is readable by the user shouldn’t affect security at all, claiming otherwise is proclaiming “security by obscurity” which is a very false assumption.

The only thing OP needs to do is to change his code to use parameterized queries and this ordeal is perfectly safe.

That being said, it’s very important to stress the fact that the user can read and modify javascript. This means you can not trust that the data and need to validate it server side as well.

I use Ajax on a regular basis and I agree with JimL that if you program correctly in PHP then you shouldn’t have no security issues (at the very least a minimum risk). What I do is get the script to work solely using PHP then when I have it functioning really good then I convert the script/HTML using AJAX. This not only leads to better security in my opinion, but graceful degradation for it will work if a user disables JavaScript (usually). You really know it’s secure if you can get the script to run solely in PHP (Taking the account that you sanitized and validated the data). Usually it’s just a few modifications and tweaks to the code and to the HTML/CSS. The problem arises in my opinion is when a person starts writing PHP and JavaScript at the same time, this in my opinion leads to security leaks (issues).

Agree, but still, security issues in PHP has nothing to do with Ajax. So while your PHP code could have more holes than swiss cheese, using Ajax or not will not add or remove any security issues.

I agree with you 100% on that, but searching the internet I find people who are more concern about getting Ajax to work that they throw PHP spaghetti code up just to see if they can get it to work. I have also seen where people validate the JavaScript portion figuring that they secured the script. Not realizing that not only you have to validate, but sanitize the PHP, since validation and sanitizing are to different things. JavaScript also can be disabled thus rendering the validation portion mute. Very frustrating. Awhile back ago I saw a JavaScript login script that supposedly did everything in JavaScript, I said to myself what a horrible script and I feel sorry for anyone who uses that on a live website. :frowning:

Sorry about going off-topic, I was just glancing at the OP script. I was wondering why a redirect was written? Since Ajax main purpose is to have no page refreshes. Of course that could had been answer in the following posts…

Thanks, My intent was to use just PHP & HTML but was repeatedly advised toward
ajax, jquery, etc.in several different ways:

Perhaps you should just create a working calculator page just in[b] HTML[/b] and JS to handle your calculations[b] first.[/b]
get the script to work solely using [b]PHP[/b] then I convert the [b]script/HTML using AJAX.[/b]
I was wondering why a redirect was written?
I progressed(???) from HTML to the PHP in attempt to insert the data.
The only thing OP needs to do is to change his code to use parameterized queries and this ordeal is perfectly safe.

I would appreciate code example. thanks

http://php.net/manual/en/mysqli.prepare.php

you can also search the forum, it has come up quite a lot :slight_smile:

I remember the early 90’s when people treated Javascript like some kind of voodoo and steered clear of it for fear of doing bad things.
Fast forward two decades later and one of the biggest players today is jQuery (souped up javascript) Ironic really.

So, my point, I feel telling people not to use AJAX because of security issues in PHP is like telling someone not to eat an apple because they don’t like oranges.

I agree with [member=71845]JimL[/member],
If your PHP is full of holes, ajax will make no difference.
If your PHP is watertight, ajax will make no difference.

I also agree with [member=57087]Strider64[/member] - if your project works in PHP then adding ajax later makes the site degrade gracefully. (security wise, it will make no difference)

[member=43746]ErnieAlex[/member] Saying ajax is not secure because you can see the source code, to use hidden fields instead, is the oddest thing I’ve ever heard?

Just my two-pence guys,
Red :wink:

now I’m feeling foolish; after going to that site and many others many times I don’t see the connection w/that page and getting the function js to php. I’m not asking for someone to write the code but it would be nice
to see how to use the function or values in php. thanks any way

JS and PHP are two completely separate animals. It’s normally done something like this:

In the php file(s) whatever data we echo will be what is returned by the ajax request from javascript
[php]<?php // /ajax/yourfile.php

$users = $db->query(‘SELECT * FROM users…’); // get some data somehow

echo json_encode($users);[/php]

[code]// javascript using Jquery

// send a get request to the domain the js file is on /ajax/yourfile.php
$.get("/ajax/yourfile.php", function(users) {
// take the response (json of users), and add it to element(s) with users class in the html dom
$(".users").html(users);
});[/code]

HTML (myform.html)

<!-- this is your form -->
<form action="update.php" method="post" id="myform">
<input type="text" name="first_element" id="first_element" value="">
<input type="submit" name="Submit" id="submit_button" value="true">
</form>

PHP (update.php)
[php]
if(isset($_POST[‘submit’])) {
// check first element is set.
if(isset($_POST[‘first_element’])) {
$first_element = trim($_POST[‘first_element’]);
}
else {
echo ‘Error: first element is not set!’;
}

$mysqli= new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE');

$query = "INSERT INTO database (columnone, datecolumn) VALUES (?, NOW())";
if($stmt = $mysqli->prepare($query)) {
    $stmt->bind_param('s', $first_element);
    if($stmt->execute() == true) {
       echo 'database updated!';
    }
    else {
        echo $mysqli->error;
    }
    $stmt->close();
}

}
[/php]

The code above is two pages, the first is the HTML that send ‘first_element’ to the PHP script upon submission. The second is the php code to check the form was submitted, check the first_element variable is set, then add the value into the database.

Now we add in our ajax.
JS

<script>
$("#submit_button").click(function(event){
   event.preventDefault(); // stop the page from changing.

   var $first_element = $("#first_element").val(); // get the value of the first_element in the form

  $.post("update.php", function($first_element,status){
    alert(status);
  });
});
</script>

As you can see, the js just grabs the data and sends it to the update.php file. I have performed no sanitization what so ever in my js file. It is all taken care of in the PHP script.

Disclaimer: I wrote this in the editor on this site, i have not tested it. (looks ok though)

Hope that helps,
Red :wink:

PS: It seems Jim and myself were writing at the same time as i got the ‘new post’ message upon submitting so please feel free to use either example.

Hi, I got led astray with the ajax, etc. I’m sure this only requiresJS and
php. I just don’t know how to send my function or its arguments to my php
file. Since JS is so verbose I’m posting succinct code
to demonstrate my path. Everything works except the values sent
to php are zeros. Thanks in advance.

(sending the form to:)

[code]


[/code]

(form submission)

[code]
calculate

<input id=“rYes” type=“radio” name=“YesNo” value=“Yes” onClick=“location.href=‘http://localhost/home/calcprint.php’;”
print

[/code]

(this is the file I’m trying to send the variables to)
[php]<?php
$servername = “localhost”;$username = “root”;$password = “cookie”;$dbname = “homedb”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{ die("Connection failed: " . mysqli_connect_error()); }
$sql = “INSERT INTO calculator (purpose, value1, op, value2, total)
VALUES (‘purpose’, ‘value1’, ‘op’, ‘value2’, ‘total’)”;
if (mysqli_query($conn, $sql))
{ echo “New record created successfully”; }
else
{ echo "Error: " . $sql . “
” . mysqli_error($conn); }
mysqli_close($conn);
header( ‘Location: http://localhost/home/calculator.html’ );
exit();
?> [/php]

Well, sorry if I was indicating that AJAX was not secure. I meant that the current code early on in this
thread when you wanted to add in AJAX would not be secure. All of the comments made by the others
were very helpful. Sorry if I was doing the late-night posting. Hmmm, as now…

Anyways, I came across a copy of some very simple code for creating an onscreen calculator that I had
stuck away somewhere. Here is the code. Nothing fancy, but, perhaps it might be useful. Just a thought…
[php]






[/php]

Hi, I got led astray with the ajax, etc. I’m sure this only requires JS and
php. I just don’t know how to send my function or its arguments to my php
file. Since JS is so verbose I’m posting succinct code
to demonstrate my path. Everything works except the values sent
to php are zeros. Thanks in advance.

(sending the form to:)

[code]


[/code] (form submission) [code] calculate

<input id=“rYes” type=“radio” name=“YesNo” value=“Yes” onClick=“location.href=‘http://localhost/home/calcprint.php’;”
print

[/code] [code]
[/code]

</body></html>

(this is the file I’m trying to send the variables to)
[php]<?php
$servername = “localhost”;$username = “root”;$password = “cookie”;$dbname = “homedb”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{ die("Connection failed: " . mysqli_connect_error()); }
$sql = “INSERT INTO calculator (purpose, value1, op, value2, total)
VALUES (‘purpose’, ‘value1’, ‘op’, ‘value2’, ‘total’)”;
if (mysqli_query($conn, $sql))
{ echo “New record created successfully”; }
else
{ echo "Error: " . $sql . “
” . mysqli_error($conn); }
mysqli_close($conn);
header( ‘Location: http://localhost/home/calculator.html’ );
exit();
?> [/php]

Well, 12Strings, everyone who has posted have explained how to handle this. Perhaps a short recap on
how JS and PHP works might help you.

Javascript is CLIENT-SIDE only. Therefore, it can only alter fields that are held inside the browser. It can
do calculations and store values as needed into fields. Therefore, it does nothing SERVER-SIDE and can’t
directly store data on your server.

Transferring data from the browser to the server can be handled, in the easy ways, by either posting the
data inside input fields using a form and sending the posted values to a PHP file that can handle storing the
values or using AJAX to basically do the same thing using a smaller PHP file that updates the database.

Therefore, you need to to either POST the form to a PHP file that would grab the values using $_POST[]
variables and store the data OR you need to call a PHP file from your JS code which would mean using the
AJAX code. Both of these are simple methods and several posts here have shown you how to do that.

In your code, you have this line:

$sql = "INSERT INTO calculator (purpose, value1, op, value2, total) VALUES ('purpose', 'value1', 'op', 'value2', 'total')";
You attempt to store data into table "calculator" using data that is invalid. In PHP, you need to use variables which are normally in the form of $purpose, $value1, $op, $value2, $total, etc... Also, these variables would need loading from the page that is posting the data. Therefore, if using a FORM and POST system, you just capture them something like: $purpose=$_POST["purpose"]; Where the name of the input field on the form page is named "purpose"... If you use the AJAX method, you create a list of the data that is sent to the PHP file. Then, the PHP file would use AJAX and JSON data to handle the data and then load the list of variables that are needed for the SQL command. Hope that makes sense...

So, your first section is a form which is set up to use POST, therefore, I think the first way would work best
and might be easier to understand than the AJAX version. In your code sample, you set up the EQUALS
button and send it to a JS function. I assume that this function handles the calculation code. In the second
section, you show a CALCULATE button that submits the form. This buttons sends the form data to the
file “calcinsert.php”. Since you did not explain which samples of your code are in which filenames, I will
assume that the “calcinsert.php” file is the last section where you store the info into the DB. If that is the
case, then, in that section you would need to add in the code that grabs the values from the form before it
is stored in the DB. If all of this is true, you would need to add some code something like this. (this is just
off the top of my head and not tested at all.)
[php]

<?php $servername = "localhost";$username = "root";$password = "xxxxxx";$dbname = "homedb"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Added lines to grab the form's values... $purpose = $_POST['purpose']; $value1 = $_POST['value1']; $op = $_POST['op']; $value2 = $_POST['value2']; $total = $_POST['total']; // Altered the INSERT to use the values pulled from the form... $sql = "INSERT INTO calculator (purpose, value1, op, value2, total) VALUES ('$purpose', '$value1', '$op', '$value2', '$total')"; // ( NOTE: notice that names in the DB do not use the dollar-sign, but, variables do... ) if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . mysqli_error($conn); } mysqli_close($conn); header( 'Location: http://localhost/home/calculator.html' ); exit(); ?>

[/php]
( I x’d out your password as you should not post that on forums. )
As you see, the form needs to have the input fields “named” correctly for the PHP code to grab the values
of them and then they are useable as PHP variables. So, this is the first way of posting data to a PHP file
using a standard form system. One further issue is that in your form code will start out blank once the PHP
code sends itself back to the HTML page. Therefore, in that page, you will have to re-insert the values into
the form’s input fields. Unless you want it to clear after each save. (That is why others would like to use
the AJAX method as it can be done dynamically. But, that means adding in the AJAX code. Either works!)

Hope that all makes sense and helps…

thanks a lot to every effort

Sponsor our Newsletter | Privacy Policy | Terms of Service