WooBin WooYeol WooBin WooYeol - 7 months ago 25
Javascript Question

OnChange Caluclations With PHP

I have an order form and once a quantity is input into the text box I want the tax and total to update appropriately. How is this done with php, or is this a javascript function that would need to be called? Just for example sake, let's say that the tax would be .3%

What I am after:

1) OnChange() of txtitem1qty populate the tax (txtitem1tax)

2) OnChange() of txtitem1qty populate the total (txtitemtotalprice)

This is the code that I have thus far that populates my order table

<html>
<body>
<form id="Form1" runat="server">
<div id="Form1" runat="server">
<table id="table1" border="1">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Tax</th>
<th>Total</th>
</tr>
<tr>
<td><label for="item1">Item 1</label></td>
<td><label for="lblitem1price">$25.00</label></td>
<td><input type="text" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
</table>
</div>
</form>
</body>
</html>

Answer

I made a example with the solution for you:

I made some necessary changes in your html, included "ids":

//html file

<tr>
                <td><label for="item1">Item 1</label></td>
                <td><label for="lblitem1price">$25.00</label></td>
                <td><input  type="text" id="item_1_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
                <td><input  type ="text" id="item_1_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
                <td><input  type="text" id="item_1_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
            </tr>

javascript in the html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script>
    function calculate(el){
        var quantity = el.val();
        var id = el.attr("id").replace("item_","").replace("_qty","");
        var data = {quantity: quantity,id:id};
        var targetTax = $("#item_"+id+"_tax");
        var targetTotalPrice = $("#item_"+id+"_totalprice");
        $.post("sandbox.php",data,function(response){
           response = JSON.parse(response);
            targetTax.val(response.tax);
            targetTotalPrice.val(response.totalprice);
        });
    }
    var qty = $("#item_1_qty");
    qty.on("keyup",function(){
        calculate($(this));
    });

</script>

my file is called sandbox, but can rename to calculate.php;

//sandbox.php

<?php

//The best way is that the data is in a database
$items = array(
    array("id"=> 1, "label"=> "Item1","value"=>25.0)
);

$tax = 0.3;
$id = isset($_POST['id'])?$_POST['id']:0;
if(!is_numeric($id)){
    $id = 0;
}
$quantity = isset($_POST['quantity'])?$_POST['quantity']:1;
if(!is_numeric($quantity)){
    $quantity = 1;
}
$finalValue = 0;
$currentItem = null;

foreach($items as $item){
    if($item["id"] == $id){
          $currentItem = $item;
    }
}

if($currentItem != null){
    $finalValue = $quantity * $currentItem["value"];
    $finalValue = ($finalValue * $tax) + $finalValue;
}

$return = array(
    'quantity' => $quantity,
    'tax' => $tax,
    'totalprice' => $finalValue
);

print json_encode($return);

UPDATE: Finding the product in database, is only an example that you can apply:

$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT p.id,p.value FROM Products p WHERE p.id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $id);
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$stmt->close();

if(!$result = $stmt->get_result()){
    die('There was an error running the query [' . $db->error . ']');
}

//$items = $result->fetch_all(MYSQLI_ASSOC);
$currentItem = $result->fetch_array();

$tax = 0.3;
$id = isset($_POST['id'])?$_POST['id']:0;
if(!is_numeric($id)){
    $id = 0;
}
$quantity = isset($_POST['quantity'])?$_POST['quantity']:1;
if(!is_numeric($quantity)){
    $quantity = 1;
}
$finalValue = 0;


if($currentItem != null){
    $finalValue = $quantity * $currentItem["value"];
    $finalValue = ($finalValue * $tax) + $finalValue;
}

$return = array(
    'quantity' => $quantity,
    'tax' => $tax,
    'totalprice' => $finalValue
);

print json_encode($return);