I have the following HTML form with input elements:
<form id="forma" name="forma" method="post">
<div id="oblock">
<div class="dtable">
<div class="drow" id="drow1">
<div class="dcell">
<label for="aster">Aster:</label>
<input type="text" id="aster" name="aster" value="0" stock="10" price="2.99" required>
</div>
<div class="dcell">
<label for="daffodil">Daffodil:</label>
<input type="text" id="daffodil" name="daffodil" value="0" stock="12" price="1.99" required >
</div>
<div class="dcell">
<label for="rose">Rose:</label>
<input type="text" id="rose" name="rose" value="0" stock="2" price="4.99" required>
</div>
</div>
</div>
</div>
<div id="buttonDiv">
<button type="submit">Place Order</button>
</div>
</form>
And I use jQuery serialize() to collect data from the form and send to the server side (test.php in my case) using $.post:
$(function() {
$("button").click(function(e) {
var formData = $("form").serialize();
$.post("test.php", formData, processServerResponse);
e.preventDefault();
});
});
function processServerResponse(data) {
$("div.dcell").hide();
$("#buttonDiv").append('<div>'+data.total+'</div>');
$("#buttonDiv button").remove();
}
If I understood correctly - with var formData = $("form").serialize(); the data that are sent to the server will be a string that will look something like this:
"aster":"2"&"daffodil":"5"&"rose":"0"
1. How to access these values in PHP?
2. If there are a large number of input elements that each has its own unique name, how can we iterate (and avoid using $_POST['input_name'] for each element individually -> $_POST['aster'], $_POST['rose'] and so on... ) and calculate the sum in PHP?
3. How to send that calculated sum back to client (from PHP to jQuery/Client side)?
EDIT2:
Based on some answers I received here, I tried the following way:
<?php
$sum = 0;
foreach ($_POST as $name=>$value) {
$sum += (int)$value;
}
$_POST['total'] = $sum;
echo json_encode($_POST['total']);
My client code (jQuery):
function processServerResponse(data) {
$("div.dcell").hide();
$("#buttonDiv").append('<div>'+data+'</div>');
$("#buttonDiv button").remove();
}
And it works - it displays the sum...