samz22
samz22

Reputation: 101

json_encode for more than 2 arrays

I have 2 tables to be retrieved from database with 2 different queries and needs to be encoded in json and send to ajax.The issue is I am not able to pass 2 json's to ajax . I have tried with echo json_encode(array($data1,$data2)); but it is not working.

//My php code

$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
    $data1['value1'] = $row['value1'];
    $data1['value2'] = $row['value2'];
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
    $data2['value2'] = $row['value2'];
    $data2['value3'] = $row['value3'];
}

  echo json_encode(array($data1,$data2)); 

//My AJAX code

$(document).ready(function(){
  $('#Form').submit(function(e){
  e.preventDefault(); // stops the form submission

  $.ajax({
     url:$(this).attr('action'), // action attribute of form to send the values
   type:$(this).attr('method'), // method used in the form
   data:$(this).serialize(), // data to be sent to php
   dataType:"json",
   success:function(data){
       //main
       alert(data.value1);
   },
   error:function(err){
       alert(err);
   }
 });

});
});

Kindly help in solving this issue.Thanks in advance

Upvotes: 1

Views: 4079

Answers (2)

Wizard
Wizard

Reputation: 3151

In PHP:

echo json_encode(array($data1, $data2));

In AJAX:

var data1 = data[0];
var data2 = data[1];
$.each(data1, function() {
    console.log(this.value1 + ',' + this.value2);
});
$.each(data2, function() {
    console.log(this.value2 + ',' + this.value3);
});

EDIT: After a whole year, I just noticed that the initial PHP code was wrong, because the loop for the sql result would overwrite each time the values of the array. So, the correct one is this:

$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
    $data1[] = array('value1' => $row['value1'], 'value2' => $row['value2']);
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
    $data2[] = array('value2' => $row['value2'], 'value3' => $row['value3']);
}

echo json_encode(array($data1,$data2)); 

Upvotes: 3

Tobias F.
Tobias F.

Reputation: 1048

Your code is fine, you just have to handle the two arrays within your success function:

success: function(data){
  var object1 = data[0];
  var object2 = data[1];

  // Do whatever you like to do with them
}

Upvotes: 0

Related Questions