/    Sign up×
Community /Pin to ProfileBookmark

Adding a dynamic AJAX script to Update the price of a PHP Variable depending on Qty

Hi everyone,

I have created a bespoke quote form which is connected to my PrestaShop Database.

I am trying to now add a Quantity field which allows the user to type in a number of their choice which will then automatically update the price of the product; for example – if Product A is £20.00 and they change the quantity to 5, then Product A becomes £100.

How can I do this? What is this best way to go about this?

Any help is greatly appreciated!

I have provided my code below:

[CODE]
<?php
$servername = ‘REMOVED’;
$username = ‘REMOVED’;
$password = ‘REMOVED’;
$dbname = ‘REMOVED’;

try {
$conn = new PDO(“mysql:host=$servername;dbname=$dbname”, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare(“SELECT id_product, price, unity FROM ps_product”);
$stmt->execute();
$product = $stmt->fetchAll();

echo ‘<div class=”table-responsive”>’;
echo ‘<table class=”table table-striped”>’;
echo ‘<th>Checkbox</th><th>Product Reference</th><th>Product Name</th><th>Price</th><th>Unit</th>’;
foreach ($product as $rowProd) {
$stmt = $conn->prepare(“SELECT reference, price FROM ps_product_attribute WHERE id_product = “. $rowProd[“id_product”] .””);
$stmt->execute();
$attribute = $stmt->fetchAll();

$stmt = $conn->prepare(“SELECT name FROM ps_product_lang WHERE id_product = “. $rowProd[“id_product”] .””);
$stmt->execute();
$name = $stmt->fetchAll();

foreach ($name as $rowName) {
$productName = $rowName[‘name’];
}

foreach ($attribute as $rowAttr) {
if($rowAttr[“price”] == 0 OR $rowAttr[“price”] < $rowProd[“price”]) {
$rowAttr[“price”] = $rowAttr[“price”] + $rowProd[“price”];
}

if($rowProd[“unity”] == false) {
$rowProd[“unity”] = 1;
}

$reference = ‘Reference’;
$price = ‘Price’;
$unit = ‘Unit’;

print ‘<tr>’;
print ‘<td><input type=”checkbox” name=”product[]” value=”‘. $rowAttr[“reference”] .’;’. $productName .’;’. number_format($rowAttr[“price”], 2) .’;’. $rowProd[“unity”] .'”></td>’;
print ‘<td>’. $rowAttr[“reference”] .'</td>’;
print ‘<td>’. $productName .'</td>’;
print ‘<td>&pound;’. number_format($rowAttr[“price”], 2) .'</td>’;
print ‘<td>’. $rowProd[“unity”] .'</td>’;
print ‘</tr>’;
}
}
echo ‘</table>’;
echo ‘</div>’;
}

catch(PDOException $e) {
echo “Error: ” . $e->getMessage();
}

$conn = null;
?>
[/CODE]

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@rootJan 24.2017 — You have only posted your PHP but no JavaScript.

Your Quantity field would be better off being a HTML5 input field for a number range that is set to allow a minimum quantity input to avoid invalid amounts like 1.1 or invalid amounts like -3, the number field has +/- buttons included but also accepts direct input. ( http://www.w3schools.com/html/html_form_input_types.asp )

Ajax can be used to pull information off the server to validate if the user has selected a quantity within the stock range limits but also change the price, apply bulk discount information. However, your input form should be submitted to the server to validate this data and spit out an order confirm screen to show the customer the order and allow for any corrections.
Copy linkTweet thisAlerts:
@AshbridgeauthorJan 24.2017 — Hello,

I haven't wrote any JavaScript as I wasn't sure if it was possible to even do what I needed to do with Javascript. I have set-up the quantity field using HTML5 but I now need something to multiply the PHP Price Variable depending on the value in the quantity box.
Copy linkTweet thisAlerts:
@rootJan 24.2017 — Well this is where things can be tricky if you have not set up a data structure for your output table to tie in together with other elements.

IMHO you should separate each item you display and name the inputs so that they are grouped. for example
[code=html]
Item: <input name="product_1234" type="text" value="Solid Gold widget 24 carat" >
Amt: <input name="product_1234" type="number" value="2000" readonly>
Qty: <input name="product_1234" type="number" value="0" onchange="calcSub(this);">
Ord Val: <input name="product_1234" type="number" value="0" readonly>
[/code]


and in the calcSub function that has been passed the object "this" will be a reference to that field that had a change made to it, this will allow you to access the fields all named, ID isn't useful as all ID attributes have to be unique where as name attributes can be many and that means you can create a field group.

here is a little demo [code=html]<!DOCTYPE html>
<html>
<head>
<title>SubTotal</title>
<script>
function calcSub( fld ){
var productName = fld.name, quantityValue = fld.value, st=0;

// get the product
var theProduct = document.forms.products[ productName ];

// value for the group of inputs
var productCost = theProduct[1].value; // gets value 2000

var subValue = quantityValue * productCost;

theProduct[3].value = subValue;

}
</script>
</head>
<body>

<div id="textrtc">
<form name="products" action="javascript:;">
<table>
<tr>
<td>Item: <input name="product_1234" type="text" value="Solid Gold widget 24 carat" ></td>
<td>Amt: <input name="product_1234" type="number" value="2000" readonly></td>
<td>Qty: <input name="product_1234" type="number" min="0" value="0" onchange="calcSub(this);"></td>
<td>Ord Val: <input name="product_1234" type="number" value="0" readonly></td>
</tr>
<tr>
<td>Item: <input name="product_2345" type="text" value="Solid Silver widget 925" ></td>
<td>Amt: <input name="product_2345" type="number" value="1800" readonly></td>
<td>Qty: <input name="product_2345" type="number" min="0" value="0" onchange="calcSub(this);"></td>
<td>Ord Val: <input name="product_2345" type="number" value="0" readonly></td>
</tr>
<tr>
<td>Item: <input name="product_3456" type="text" value="Solid Wood widget (pine)" ></td>
<td>Amt: <input name="product_3456" type="number" value="15.99" readonly></td>
<td>Qty: <input name="product_3456" type="number" min="0" value="0" onchange="calcSub(this);"></td>
<td>Ord Val: <input name="product_3456" type="number" value="0" readonly></td>
</tr>
</table>

</form>

</div>
</body>
</html>[/code]


The idea being that the quantity changes updates just the field sub total for that product and uses a single name to group the fields data together for easier manipulation. the readonly flag is set to stop any manipulation of the totals and product values.

All you would then need is to add an update routine to the order value and add any revenue for taxes, postage, then that form is submitted to the server to validate that it is correct and then you would display a confirm order screen before finally submitting the order to the server to process.
Copy linkTweet thisAlerts:
@AshbridgeauthorJan 24.2017 — I don't suppose you have Skype where I could share some in-depth code with you?

I can't quite explain the entire process here; my PHP form sends data to a .TXT file and then to a .PDF. I can't visualize how I would get this working with your exact example.
Copy linkTweet thisAlerts:
@rootJan 24.2017 — I am afraid I don't and my ISP does not allow VoIP clients as its a mobile network I use for my internet, they expect you to use your phone to use your phone credit.

If you are creating a PDF form, then you should look at the PDF actionScript from adobe as its not the same as JavaScript and having tried making a PDF web based form in the past that allowed submission to the server, its not a straight forward process and depending on your version of PDF form created will result in some behaviour.

You can use same sort of coding ideas but you would need a PDF that has scripting embedded in the form.
×

Success!

Help @Ashbridge spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...