1

I am throwing entity object to javascript by ajax

in php

// obtaining object by doctrine2
$lesson = $em->getRepository('Lesson')
    ->findOneBy(array('id' => $myId));

// $lesson->getName(); // I can access the entity property here like this.

//throwing object as json
$response = array("responseCode" => 200,'lesson' => $lesson,"success" => true);
return new Response(json_encode($response),200,array('Content-Type'=>'application/json'));

in javascript

function reloadItems(){
    var url= "http://myajax.com/ajax/";
    $.post(url,something,function(data){
// I got lesson object from php as json here.

// however these doesn't work
//      console.log(data.lesson.name);
//      console.log(data.lesson.getName);

    });

How can I get the each repository data in javascript??

3
  • just console.log(data.lesson) and check the console browser, to get a proper outlook of the response, you should add it on the question Commented Apr 11, 2015 at 10:45
  • console.log(data.lesson); shows ' Object {} ' on Chrome. Commented Apr 11, 2015 at 12:16
  • odd, check out the network tab and check for the response, and just check console.log(data), also debug PHP if its empty or not Commented Apr 11, 2015 at 12:21

1 Answer 1

2

When passed an object, json_encode can only grab the public properties. Methods are ignored completely. Since $lesson is a doctrine entity then I'm sure Lesson::name is either private or protected.

There are some serializer tools like http://symfony.com/doc/current/components/serializer.html which use reflection to access private/protected variables.

Or you can use PHP's (>=5.4) json serializer http://php.net/manual/en/jsonserializable.jsonserialize.php

Something like:

class Lesson implements \JsonSerializable
{
  private $name;

  public function jsonSerialize() 
  {
    return 
    [
      'name' => $this->name,
    ];
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I understood basically, can't convert php method to json object. I will research work around way you mentioned. thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.