2

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...

PeraMika
  • 3,539
  • 9
  • 38
  • 63
  • 1
    1. You'd access them with the superglobals, using the elements names as keys, as in `$_POST['aster']` – adeneo Dec 07 '15 at 15:12
  • Regarding your added/updated question: Change value.total to data.total – Andy Dec 07 '15 at 16:11
  • Changed and I am getting displayed `undefined` instead of sum? – PeraMika Dec 07 '15 at 16:14
  • Can you show what is returned from your php script? And remember, when you use serialize() only the input elements value is sent with the request. Not your added attributes stock or price – Andy Dec 07 '15 at 16:26
  • @Andy Right now, I am watching firebug net panel and there is nothing send back from PHP to jQuery(flowers.html with all this jQuery code): http://s14.postimg.org/43sev48ts/netpanel.jpg – PeraMika Dec 07 '15 at 16:33
  • 1
    Ok, I can't see any element in your html code with the name uneteVrednosti bur you check for it in your php code with isset($_POST['uneteVrednosti']). Try to add a hidden element with that name to your form – Andy Dec 07 '15 at 16:41
  • @Andy I just removed that part with checking if it's set... And still, no response from PHP (test.php) is sent. – PeraMika Dec 07 '15 at 16:49
  • @Andy This is how I did it in PHP: `$_POST['total'] = $sum; echo json_encode($_POST['total']);` and in jQuery code I just changed from `data.total` to just `data` and it works. Anyway, I'll check your answer to correct and thank you so much!!! – PeraMika Dec 07 '15 at 17:13
  • @PeraMika You are welcome, great that it works! You should avoid assigning new values to $_POST. It will work but isn't very good practise. And in this case it's better to just do echo $json_encode($sum); – Andy Dec 07 '15 at 18:24

4 Answers4

1

1 With $_POST['variable-name'];

$asterPostVariable = $_POST['aster'];

2 Iterate over the $_POST array

foreach ( $_POST as $key => $val )
{
  // Do calculation, your value from input element is in $val
  $sum += $val;
  // You could also check your $key if you don't want to sum all post variables
}

3 echo it back as json data

echo json_encode( ['sum' => $calculatedSum] );

EDIT

2 Iterate over the $_POST array

foreach ( $_POST as $key => $val )
{
  // You could also check your $key if you don't want to sum all post variables. This solution is based on that your form elements that you want to calculate are named with the initial fl_
  if ( substr($key, 0, 3) == 'fl_' )
    $sum += $val;

}
Andy
  • 397
  • 2
  • 8
  • What if this form has more variables (unrelated to flowers) that are sent to server side, but we do not want to use them to calculate the sum? – PeraMika Dec 07 '15 at 15:33
  • 1
    Maybe you can name all input elements with a starting fl_ that you want to sum up up. Then in your php code you check the $key variable for the elements name. if (substr($key, 0, 3) == 'fl_') – Andy Dec 07 '15 at 16:03
1

To answer all three your questions:

1. To access the values, you would use the superglobal variables. For example:

$_POST['element_name'];

2. To iterate through all elements, use the foreach statement. For example:

$sum = 0;
foreach($_POST as $name => $value){
    $sum += strtoint($value);
}
$final = array(
    sum => $sum
);

3. To return the values back to the JavaScript, use json_encode together with echo. Also make sure not to echo any data that you don't want to return. For example:

echo json_encode($final);
Jacques Marais
  • 2,666
  • 14
  • 33
  • What if this form has more variables (unrelated to flowers) that are sent to server side, but we do not want to use them to calculate the sum? – PeraMika Dec 07 '15 at 15:33
1

You can have each of your flower variables be the index of an array:

<form id="forma" name="forma" method="post">
   <div id="oblock">
      <div class="dtable">
        <div class="drow" id="drow1">
            <div class="dcell">
                <label for="flowers[aster]">Aster:</label>
                <input type="text" id="flowers[aster]" name="flowers[aster]" value="0" stock="10" price="2.99" required>
            </div>
            <div class="dcell">
                <label for="flowers[daffodil]">Daffodil:</label>
                <input type="text" id="flowers[daffodil]" name="flowers[daffodil]" value="0" stock="12" price="1.99" required >
            </div>
            <div class="dcell">
                <label for="flowers[rose]">Rose:</label>
                <input type="text" id="flowers[rose]" name="flowers[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 then you can iterate over this array:

foreach($_POST['flowers'] as $flowerType => $count){
    // do something
}

I would try to avoid iterating over the entire array of $_POST as you may want to add more variables (unrelated to flowers) to this form later on.

You can use echo json_encode($result); when sending it back to the client

EDIT:

If you're getting an undefined response to your post, you should check your PHP error logs as it's likely that your script is failing or exiting before echoing anything out.

bzrk
  • 105
  • 1
  • 6
  • As of PHP 5.4 you can also use the short array syntax, which replaces array() with []. [Source](http://php.net/manual/en/language.types.array.php) – Andy Dec 07 '15 at 16:47
-1
  1. You shouldn't have to unserialize anything in PHP from the jquery serialize method. If you serialize the data, it should be sent to PHP as query parameters if you are using a GET method ajax request or post vars if you are using a POST ajax request. So in PHP, you would access values like $_POST["varname"] or $_GET["varname"] depending on the request type.

The serialize method just takes the form elements and puts them in string form. "varname=val&var2=val2"

  1. Iterate the request param $_REQUEST or $_POST.
  2. convert it to json and echo it back ex. echo json_encode($data);
Tariq Albajjali
  • 327
  • 1
  • 6
  • 16