简体   繁体   中英

pass html form elements as arguments to a php function

I'm trying to calculate profit, which will be dynamically shown when user input other details. But not able to understand how exactly pass the inputs to the php function & then write it back to a form element. Here is what I've done till now.

<form action="invoice.php" method="get">
    <input class="form-field" type="date" name="date" value="" placeholder="Date" id="date">
    <input class="form-field" type="text" name="product_name" value=""placeholder="Product Name" id="product_name">
    <input class="form-field" type="text" name="units" value="" placeholder="Product Unit" id="product_unit">
    <input class="form-field" type="text" name="wholesale_price" value="" placeholder="Whole Sale Price" id="wholesale_price">
    <input class="form-field" type="text" name="sell_price" value="" placeholder="Sell Price" id="sell_price">
    <input class="form-field" type="text" name="" value="" placeholder="Profit" id="profit">
    <script>
        var units = parseFloat(document.getElementById("product_units"));
        var wholesale_price = parseFloat(document.getElementById("wholesale_price"));
        var sell_price = parseFloat(document.getElementById("sell_price"));
        document.getElementById("profit").value = profit_calculation(units, wholesale_price, sell_price);
        function profit_calculation(units, wholesale_price, sell_price) {
            return (units * sell_price) - (units * wholesale_price);
        }
    </script>
</form>

& the invoice.php,

<?php
$unit = $_GET["units"];
$wholesale = $_GET["wholesale_price"];
$sell = $_GET["sell_price"];

function invoice_profit($units, $wholesale, $sell) {
    return ($unit * $sell) - ($unit * $wholesale);
}

echo "Invoice #0001";
echo "<table border='1' align='center'>";
echo "<tr>";
echo "<td>" . $_GET["date"] . "</td>";
echo "<td>" . $_GET["product_name"] . "</td>";
echo "<td>" . $_GET["units"] . "</td>";
echo "<td>" . $_GET["wholesale_price"] . "</td>";
echo "<td>" . $_GET["sell_price"] . "</td>";
echo "<td>" . invoice_profit($units, $wholesale, $sell) . "</td>";
echo "</tr>";
echo "</table>"
?>

So basically, units, wholesale_price & sell_price will be passed to php function, profit will be calculated & written back to respective form id. Please help.

You will need ajax to send back the invoice from the server to the client. Please learn more about ajax and jquery a little google search.. of tutorials you will get thousands of them.

<script src="https://code.jquery.com/jquery-3.2.1.min.js"
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous"></script>
<form>
    <input class="form-field" type="date" name="date" value="" placeholder="Date" id="date">
    <input class="form-field" type="text" name="product_name" value="" placeholder="Product Name" id="product_name">
    <input class="form-field" type="text" name="units" value="" placeholder="Product Unit" id="product_unit">
    <input class="form-field" type="text" name="wholesale_price" value="" placeholder="Whole Sale Price" id="wholesale_price">
    <input class="form-field" type="text" name="sell_price" value="" placeholder="Sell Price" id="sell_price">
    <input class="form-field" type="text" name=""  placeholder="Profit" id="profit">
    <button type="submit" formmethod="POST"> Calculate Profit</button>
</form>
<div id="invoice"></div>
<script>
    $('document').ready(function(){

            $('button').on('click',function(event){

                event.preventDefault();

        var units= $("#product_unit").val();
        var wholesale_price=$("#wholesale_price").val();
        var sell_price=$("#sell_price").val();

            var profit = (units*sell_price)-(units*wholesale_price);

                $('#profit').val(profit);


                var data = $('form').serialize();

                $.ajax({

                    type : "POST",
                    data : data,
                    url : "invoice.php",
                    dataType : "html",
                    success : function(response){

                        $('#invoice').html(response);
                    },

                    error : function(obj){

                        console.log(obj);
                    }

                });

            });
    });
</script>

invoice.php

<?php
$unit      = $_POST["units"];
$wholesale = $_POST["wholesale_price"];
$sell      = $_POST["sell_price"];


function invoice_profit($units, $wholesale, $sell)
{
    return ($units * $sell) - ($units * $wholesale);
}

echo "Invoice #0001";
echo "<table border='1' align='center'>";
echo "<tr>";
echo "<td>" . $_POST["date"] . "</td>";
echo "<td>" . $_POST["product_name"] . "</td>";
echo "<td>" . $_POST["units"] . "</td>";
echo "<td>" . $_POST["wholesale_price"] . "</td>";
echo "<td>" . $_POST["sell_price"] . "</td>";
echo "<td>" . invoice_profit($unit, $wholesale, $sell) . "</td>";
echo "</tr>";
echo "</table>";
?>

Results :

在此处输入图片说明

Then you will have to style the table according to your design

You must first choose where you will do the job. It can be on the server or on the browser. You have created two functions that return the answer in PHP and in JS. The one in PHP has a small bug in the code. You have put $unit instead of $units

$units     = $_GET["units"];
$wholesale = $_GET["wholesale_price"];
$sell      = $_GET["sell_price"];

function invoice_profit($units, $wholesale, $sell) { // old code: $unit
   return ($units * $sell)-($units * $wholesale); // old code: $unit    
}

But this will need a submit the form to calculate the profit. Another way is to use only JS. For this you will need and id in the HTML or an element like this:

echo "<td><input type=\"text\" id=\"the_profit\" value=\"".invoice_profit($units, $wholesale, $sell).."\"></td>";

Then the JS will change this way:

function profit_calculation(){
  var units= parseFloat(document.getElementById("product_units"));
  var wholesale_price=parseFloat(document.getElementById("wholesale_price"));
  var sell_price=parseFloat(document.getElementById("sell_price"));
  document.getElementById('the_profit').value = (units*sell_price)-(units*wholesale_price);     
}

Now to do the calculation we need to invoke the JS function somewhere. If you want every change to recalculate profit then something like this can be done with every form field :

   <input class="form-field" type="date" name="date"
          value="" placeholder="Date" id="date"
          onchange="return profit_calculation();">

Note that the variables are now local to the function and take the data from the form on every change. But in JS and in PHP you have to check if the data is valid also. If you don't JS can give you NaN or undefined, so the answer I give has still some things more to be done.

Hope that helps,

B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM