How to pass an array of StdClass php objects to a JS variable using $ .ajax () jquery

4

I have the structure below. I need to access each value in jquery.

Array
(
    [0] => stdClass Object
        (
            [post_id] => 140
        )

    [1] => stdClass Object
        (
            [post_id] => 141
        )

    [2] => stdClass Object
        (
            [post_id] => 142
        )

)
    
asked by anonymous 20.10.2015 / 21:06

2 answers

2

Convert object to JSON when responding to jQuery:

<?php

$o1 = new stdClass;
$o1->post_id = 140;

$o2 = new stdClass;
$o2->post_id = 141;

$arr = array($o1, $o2);

echo json_encode($arr);
// [{"post_id":140},{"post_id":141}]
    
20.10.2015 / 21:10
2

Take this array, send it as a json to javascript

<?php
   $arr = array(array('id' => 1 ), array('id' => 2 ), array('id' => 3 ));
   echo json_encode($arr);

In javascript transform this string into a json and then you can access it as per the code below. In% do% change this by a variable in 1 .

.done(function(msg) {
      var response = JSON.parse(msg);
      alert(response[1].id);
//demais códigos ...
    
20.10.2015 / 21:17