PHP Calculator with Dynamic Calculations

I need to create an order form that updates the tax and total automatically once a quantity is entered into the text box. Should I use PHP or JavaScript for this functionality? Let's assume, for instance, that the tax rate is 0.3%

My requirements:
1) When txtitem1qty changes, update the tax (txtitem1tax)
2) When txtitem1qty changes, update the total (txtitemtotalprice)

This snippet of code generates 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 №1

Here is an example with a solution provided for you:

I have made some necessary adjustments to your HTML, including the addition of "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 within 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>

The filename in my code is called sandbox, but you can rename it to calculate.php;

//sandbox.php

<?php

//It's advisable that the data resides 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: The process of finding a product in the database serves as just an example that you can implement:

$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);

$stmt->execute();

$stmt->close();

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

$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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

When you download a file through the unpkg CDN, the size of the npm package is

I am experiencing a discrepancy with the file size of a file in my npm package. The file is 307kb in size, but when I download it through unpkg, the same file is only 73.2Kb. I find it quite puzzling how the file can be smaller when downloaded over the net ...

What is the best way to calculate the variance between the most recent and previous data points in an array in the span of an hour using JavaScript

Here is an array of objects I am working with: 0: {time: '2021-12-02T23:53:54.062Z', value: 558316} 1: {time: '2021-12-03T00:53:53.959Z', value: 558452} 2: {time: '2021-12-03T01:53:53.934Z', value: 558588} 3: {time: '2021 ...

Can AdonisJS 4.1.0 support conditional queries?

I am exploring the capabilities of AdonisJs query builder by referring to their documentation at Currently, I am attempting to replicate a scenario similar to the one demonstrated under the 'Conditional Queries' section: const query = Database. ...

Concealing items in a loop using Javascript

I need assistance with this issue. I am trying to hide text by clicking on a link, but it doesn't seem to be working correctly. Even though I tried the following code, I can't figure out why it's not functioning as expected. Is there a diff ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Navigating to a different directory using Node.js and ExpressJS route mapping

I'm struggling with setting up routing using ui.router. This is the structure of my folders: https://i.stack.imgur.com/Fu0A9.png In the app.js file within the javascripts folder, I have the following code: var app = angular.module('testing&ap ...

When running npm install, the dist folder is not automatically generated

I found a helpful tutorial at this link for creating a Grafana plugin. However, when I tried copying the code from this link to my test server (without the dist/ folder) and ran npm install, it did not generate a new dist/ folder but created a node_module ...

Utilize the Webstorm debugger in conjunction with node.js for seamless debugging

Several weeks ago, I attempted to get the webstorm debugger up and running, but unfortunately, it didn't work. Now, I'm giving it another shot, but I'm faced with the same outcome. I am following the instructions outlined here: http://www.j ...

Obtaining multiple values: Utilizing array versus modifying referenced parameters

Whenever I need to return multiple values as a result of my function (for example, a boolean indicating the success of a specific operation and a message detailing the error or success message), I often ponder the most effective method. Should these multip ...

Encountering the error message ERR_CONNECTION_TIMED_OUT while using Vue CLI

Currently, I am venturing into the world of Vuex and attempting to incorporate some API requests using this state management pattern. Here is the structure I have set up: Component.Vue export default { created() { this.$store.dispatch('getDat ...

Display various post types in a WordPress loop

I am designing a website on Wordpress where I want to showcase various "tiles" containing content from different sections of the site on the homepage. These tiles are custom post types such as "services", "consultants", and "blog posts". While I understan ...

How to use an array of parameters with Yii2's createUrl() function?

As per the instructions provided in the Yii2 documentation, the recommended way to construct a URL is as follows: $appUrl = Yii::$app->urlManager->createUrl([Yii::$app->controller->id . '/' . Yii::$app->controller->action->i ...

Guide on connecting MySQL 'id' to an HTML element

I need assistance with setting up a functionality on my website. I have a database containing rows of data, and each row has an 'ID' field in MySQL. I want to connect each ID to a button so that when the button is clicked, a PHP script will run t ...

Using Vue Formulate to effortlessly upload multiple images

One of my projects involves using a Vue Formulate component for uploading multiple images to an Express.js backend. Here is the code snippet for the Vue Formulate component: <FormulateInput type="image" name="property_ ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

Tips for iterating through a nested object in JavaScript with the forEach method

Here is my answer to the query. In this snippet, results represents a freshly initialized array. The object address nests within the user object. response.data.forEach(user => { results.push({ id: user.id, name: user.n ...

Troubleshooting a Problem with the Horizontal Scrollbar in Dynamic jqGrid

Currently, I am working on an ASP.net MVC project where I have implemented both dynamic and static jq grids. However, I am encountering an issue with the horizontal scroll bar in my application. To address this problem, I attempted to modify the overflow ...

Obtain the authenticated user's information through the use of AuthSub in Zend

Currently, I am utilizing Zend Gdata to establish connections between users and a shared Google Docs spreadsheet. This spreadsheet functions as the backend for a custom interface. My objective is to keep track of the user who most recently modified the va ...

Encountering a null sessionId exception with Selenium RC while attempting to activate the JQuery AddLocationStrategy feature

I've been struggling all day to activate JQuery locators in Selenium RC by trying various suggestions found online, but unfortunately, without any success. I followed the recommendations from this thread on enabling JQuery locators: How do I add a JQ ...