How to pass an object from php to javascript?

You can convert the PHP object to an array, and then use JSON function to encode it. After that, decode it from JavaScript

1. Code:

 <?php
class MyExample implements JsonSerializable {
    public $title = 'Convert object php to JS';
    public $content = 'this example will you convert an object php to object javascript';

    public function jsonSerialize () {
        return array(
            'title'=>$this->title,
            'content'=>$this->content
        );
    }
}

$myExampleInstance= new MyExample();
$myExample = json_encode($myExampleInstance); // {"title":"Convert object php to JS","content":"this example will you convert an object php to object javascript"}
echo $myExampleInstance;
?> 
<script>
var data = '<?php echo json_encode($myExampleInstance); ?>';
var obj = JSON.parse(data);
alert(obj.title);
alert(obj.content);
</script>

2. Basic steps:

You can convert the PHP object to an array, and then use JSON function to encode it. After that, decode it from JavaScript. Here are some basic steps:

  1. Convert the PHP object to an array.
  2. Using json_encode() to encode that PHP array.
  3. Pass JSON-encoded data to PHP
  4. Decode JSON from JavaScript using JSON.parse or you can use jQuery.parseJSON to do that.