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

Asked

Viewed 579 times

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
        )

)

2 answers

2


Convert the 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}]
  • 3

    to assist the colleague: http://ideone.com/sMTVM2

2

Take this array, send as a json to javascript

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

In javascript turn this string into a json and then you can access it according to the code below. In 1 exchange this for a variable in for.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.