开发者

PHP Ajax how correct use of explode

I have a form and I want the calculations to be done via ajax and PHP. I do not think I am using the explode value properly. I can't work out how to separate these in the PHP file and return a calculation of the results. The 'products' are loaded in via ajax so we do not know the id's but for the sake of this example I will put some in.

<script type="text/javascript">function test() {        

        var price1682 = 300;
        var quant1682 = $('#product_quantity_PRI_1682');

        var price2572 = 0;
        var quant2572 = $('#product_quantity_PRI_2572');

        var price2573 = 0;
        var quant2573 = $('#product_quantity_PRI_2573');
                var dataString = 'price1682=' + price1682+'&quant1682=' + quant1682+'&price2572=' + price2572+'&quant2572=' + quant2572+'&price2573=' + price2573+'&quant2573=' + quant2573+'&end=' + 'end' ;
        $.ajax({
            type: 'POST',
             url: 'http://www.divethegap.com/update/wp-content/themes/master/functions/totals.php',
             data: dataString,
             beforeSend: function() {
                 $('#results').html('processing');
                 },
             error: function() {
                 $('#results').html('failure');
                 },
             success: function(alphas) {
                 $('#results').html(alphas);
             }

        });
}</script>

and t开发者_StackOverflow社区he PHP

<?php
$str = $_POST['dataString'];
print_r (explode(",",$str));
       ?>

Now the results are Array ( [0] => ) and thats it.

What I want is to multiply each quantity by each price and then add all that together and return a total but at the moment I can't even get a functioning array. Obviously gone wrong somewhere.

Any ideas?

Marvellous


var dataString = 'price[1682]=' + price1682+'&quant[1682]=' + quant1682+'&price[2572]='
+  price2572+'&quant[2572]=' + quant2572+'&price[2573]=' + price2573+'&quant[2573]='
+  quant2573+'&end=' + 'end' ;

Now results are in:

print_r($_POST['price']);
print_r($_POST['quant']);

UPD:

foreach($price as $id => $p) {
   // Current id
   $id;
   // Current price
   $p;
   // Current quantity
   $_POST['quant'][$id];

   // Miltiply:
   $somevar = $p * $_POST['quant'][$id];
}

Dont forget to check all _POST[price] / _POST[quant] vars are integer

Final Version

<?php
$totalprice = 0;
foreach($_POST['price'] as $id => $price) {
   // Current id:
   // $id;
   // Current price:
   // $price;
   // Current quantity:
   // $_POST['quant'][$id];
   // Multiply:
   $somevar = $price * $_POST['quant'][$id];
   $totalprice += $somevar;

}
echo $totalprice;
?>


You're expanding on the , when you should be expanding on the &. Change the explode to

explode("&",$str);

and it should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜