tags:

views:

69

answers:

3

i am sending 5 different data across to a php file through POST method. the data is all integers. i want to add up all these integer values to produce a sum.

    $.post(
        "user_submit.php", 
        {score: $('#ques'+qn).find('input[name=vote]:checked').val() }, 
        function(data){
            $("#ques"+qn).hide();
            ++qn;
            $("#ques"+qn).show();
        });
    });

in the php file:

$score = $_POST['score'];
$total = $total + $score;
echo $total;

it is not adding up the values. what am i doing wrong?

+2  A: 

If you were to print_r($_POST['score']), you would see that it's actually an array, not a single value. Try something like $total += array_sum($_POST['score']); instead.

bkuhns
Sorry, see the other answers about decoding the JSON serialized string first. I forgot jQuery does that.
bkuhns
+1  A: 

$.post from jQuery submits a JSON encoded string to the server; you're actually submitting a javascript array which needs to be handled via json_decode first, and then manipulated second.

As the other posters suggested, doing a print_r($_POST['score']) would have shown this very clearly.

Erik
A: 

bkuhns is on the right path. your score isnt goin gto be any array though i dont think. AFIK $.searialize isnt recusive so youre going to get a score of 'Object'. try using this for the data.score key of your $.post:

function(){
  var score = new Array(); 
  $('#ques'+qn).find('input[name=vote]:checked').each(function(){
   score.push($(this).val());
  });
  return score.join(',');
}

and in php:

$scores = explode(',',$_POST['score']);

then loop through $scores adding to $total. or you could use array_sum as bkuhns suggests.

prodigitalson
Yep, I forgot about the JSON serialized string part. Once the string's decoded though, `array_sum()` will be your easiest solution.
bkuhns