1

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?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

The 2nd assignment also has a double equal, so it's never assigning the answer id.
See my edit for the output i get from changing ansers to an array
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.