Ali
Ali

Reputation: 267317

Passing associative array through AJAX to PHP

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?

Upvotes: 1

Views: 5688

Answers (3)

Paolo Bergantino
Paolo Bergantino

Reputation: 488734

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.

Upvotes: 6

Brent
Brent

Reputation: 521

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();
   }

Upvotes: 3

bdl
bdl

Reputation: 1502

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.

Upvotes: 0

Related Questions