Aoi
Aoi

Reputation: 1045

retrieving 2 arrays from php to ajax

I'm trying to retrieve two arrays from PHP using AJAX, but I thought that json_encode can only have one variable. Do you have any idea how I can solve this? I'm a newbie using json_encode

<?php
while($row = mysql_fetch_array($get_grades_boy)){

                $data_grades_boys[]=array(
                    'fname_b'=>$row['firstname'],
                    'mname_b' => $row['middlename'],
                    'lname_b' => $row['lastname'],
                    'studnt_id_b' => $row['student_id'],
                    'grade_b' => $row['grade'],
                    ); 
             }

             while($row2 = mysql_fetch_assoc($get_grades_girl)){

                $data_grades_girls[]=array(
                    'fname_g'=>$row2['firstname'],
                    'mname_g' => $row2['middlename'],
                    'lname_g' => $row2['lastname'],
                    'studnt_id_g' => $row2['student_id'],
                    'grade_g' => $row2['grade'],
                    ); 
             }
echo json_encode($data_grades_boys);

I tried doing this

  echo json_encode($data_grades_boys);
echo json_encode($data_grades_girls);

to retrieve but it didn't work.

Upvotes: 0

Views: 101

Answers (1)

AlecTMH
AlecTMH

Reputation: 2725

You need to combine the both arrays into a single array:

$data_grades = array(
    'boys'  => $data_grades_boys,
    'girls' => $data_grades_girls
);
echo json_encode($data_grades);

and jquery:

$ajax(
...
success: function(data) {
    boys = data.boys;
    girls = data.girls

then

$.each(boys).function(index, value) {

Upvotes: 1

Related Questions