0

I want to retrieve array for my ajax function using json_encode in Laravel PHP, but the problem is i need to send 2 multidimensional array from my controller so i can do nested loop inside my ajax using those 2 different multidimensional array,

the ajax simple example (this is my wrong version):

function getData() {
       jQuery(document).ready(function() {
           jQuery.ajax({
               url: "test",
               type: 'GET',
               data: {counter : ctr},
               dataType: "json",
               success: function(data1,data2) {
                $.each(data1.length, function(i, item) {
                  alert(data1[i].test1);
                  $.each(data2, function(i, item) {
                      alert(data2[i].test2);
                  });​
                });​
               },
               error: function(data) {
               }
           });
       });
   }

sending data php using json_encode code:

$data1 = array
  (
  array("test1",22,18),
  array("wow",15,13));

  $data2 = array
    (
    array("test2",22,18),
    array("ish",15,13));

    echo json_encode(???);
Idham Choudry
  • 589
  • 10
  • 31

2 Answers2

1

You can do in one array like below

$data = array (
        array (
            array("name" => "test1", "value" => array(22,18)),
            array("name" => "wow", "value" => array(15,13))
        ),
        array (
            array("name" => "test2", "value" => array(22,18)),
            array("name" => "ish", "value" => array(15,13))
        )

    );
// return your resoponse using laravel function instead of json_encode (this will include json header as well)
return response()->json($data)

Your jquery success function will be like below

success: function(data) {
    $.each(data, function(i, item) {
        // item for data 1
        $.each(item[i], function(i, row) {
            console.log(row.name)
            console.log(row.value)
        })
    });​
},

Please take not that i have improve the array in php structure to be more easier to read by jquery and more dynamic

xmhafiz
  • 3,482
  • 1
  • 18
  • 26
0

Try this code:

$arr = array(array($data1),array($data2));
echo json_encode($arr , JSON_FORCE_OBJECT);
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
Neeraj Prajapati
  • 541
  • 5
  • 24
  • can u give me an example how can i use it in jquery ajax function for nested loop? – Idham Choudry Aug 16 '16 at 07:56
  • why not you use .each function of jQuery or see link http://stackoverflow.com/questions/13020258/reading-nested-json-via-ajax-with-jquery-or-javascript-and-outputting-to-tables – Neeraj Prajapati Aug 16 '16 at 08:01