views:

539

answers:

3

I'm trying to pass this to a PHP script through AJAX:

  var answers={};
  for (x=0; x< allAnswers.length; x++)
   {
       answers.x=new Array();
       answers.x['id']==allAnswers[x]['id'];
       answers.x['val']=$("#field_" + x).val();
   }

   var data={};
   data.id=questions[qId]['id'];
   data['answers']=answers;

   $.post('index.php',data);

The PHP is set to print_r($_POST), and this is the output:

answers [object Object]

id       3

What am I done wrong?

Edit: Changing the code to use arrays, i.e:

  var answers=new Array();
   for (x=0; x< allAnswers.length; x++)
   {
       answers[x]=new Array();
       answers[x]['id']=allAnswers[x]['id'];
       answers[x]['val']=$("#field_" + x).val();
   }
   var data={};
   data.id=questions[qId]['id'];
   data['answers[]']=answers;

   $.post('index.php',data);

Gives this print_r:

Array
(
    [id] => 3
    [answers] => Array
        (
            [0] => 
            [1] => 
        )

)

Thoughts?

A: 

Ah that makes more sense; the way you had it formatted previously didn't match the input.

Anyhoo, the answers object is a JavaScript object; PHP doesn't know how to handle it. I suggest you parse out the individual items prior to passing to PHP, or use json_decode() on the PHP side.

bdl
+3  A: 

You're redeclaring answers.x over and over so you're only going to get the last one. x is the actual variable name and not the value you're thinking. Also you have a double equal on the "allAnswers" line. try:

var answers = new Array();
for (x=0; x< allAnswers.length; x++)
   {
       answers[ x ]=new Array();
       answers[ x ]['id'] = allAnswers[x]['id'];
       answers[ x ]['val'] = $("#field_" + x).val();
   }
Brent
The 2nd assignment also has a double equal, so it's never assigning the answer id.
Paolo Bergantino
Nice catch, fixed, thanks.
Brent
See my edit for the output i get from changing ansers to an array
Click Upvote
+2  A: 

Replace this:

var answers=new Array();
for (x=0; x< allAnswers.length; x++) {
    answers[x]=new Array();
    answers[x]['id']=allAnswers[x]['id'];
    answers[x]['val']=$("#field_" + x).val();
}

With this:

var answers = new Array();
for (x=0; x< allAnswers.length; x++) {
    answers[x] = {};
    answers[x]['id']=allAnswers[x]['id'];
    answers[x]['val']=$("#field_" + x).val();
}

You want an array of objects, not an array of arrays.

Paolo Bergantino