31

I have objects in php that each represents a "item" and all info associated with it.

And when the user browses the page, these objects should be passed to javascript. Ideally, mirroring the same structure, so I can use Raphael to display each item and its info as separate shapes on my site.

However, how do you get an object from php to javascript?

William Sham
  • 12,849
  • 11
  • 50
  • 67

4 Answers4

41

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.

This is an interesting tutorial about passing a JavaScript object to a PHP object. You might find it useful by watching some other featured/related videos.

Hope this helps.

Community
  • 1
  • 1
  • 6
    `eval()` is evil. Don't use it unless you can't help it, and especially do not use it on untrusted data! – Bobby Jun 12 '13 at 09:56
  • Indeed, eval() is a dangerous method to call and also, if the object is quite big, it can be very slow to process. It would be better if you ignore it's existance because in most case, if you need to use it for it's real purpose, it's because you have an architecture problem. – RPDeshaies Feb 21 '14 at 13:43
  • best answer ! works like a charm – Cristian Cardoso May 27 '17 at 17:11
  • There's no need for step 1 (convert the PHP object to an array). json_encode() works fine on objects. – Paul Chris Jones Jan 10 '22 at 09:28
24

I use this:

<script>
var js_data = '<?php echo json_encode($php_data); ?>';
var js_obj_data = JSON.parse(js_data );
</script>

$php_data can be since simple arrays to arrays of objects.

dlopezgonzalez
  • 4,217
  • 5
  • 31
  • 42
  • 2
    `$php_data['foo'] = "'";` and `$php_data['foo'] = '"';` will give you problems. `Uncaught SyntaxError: Unexpected string in JSON at position`. Why not `var js_data = ;` and skip the JSON.parse ? – Geza Turi Jun 30 '19 at 16:06
23

Late answer, but I am very surprised no one mentioned what is, arguably, the "correct" way to deploy this functionality.

Implement the JsonSerializable interface on your object. This interface defines one abstract method, jsonSerialize. That method should return the array representation of your object.

The jsonSerialize will be called when you attempt to use json_encode on the object. You can think of this interface as a sort of "magic method" specific to the native JSON encode function, equivalent to __toString for strings.

Putting it in action, you have an object that looks like this:

class MyFoo implements JsonSerializable {
    public $bar = 'hello';
    public $baz = 'world';

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

$myFooInstance= new MyFoo();
echo json_encode($myFooInstance); // {"bar":"hello","baz":"world"}

When I am implementing this in my projects, I usually put a toArray method in the objects, which generates the array, and I have jsonSerialize use it:

public function jsonSerialize () { return $this->toArray(); }

...this way I can also make use of the array form, if I so choose. This is also handy if you'll be implementing object serialization with __sleep

Documentation

ajmedway
  • 1,492
  • 14
  • 28
Chris Baker
  • 49,926
  • 12
  • 96
  • 115
3

You will be using JSON to encode the PHP objects so that they can be accessed by Javascript. The specifics on how to do that depends on your application.

PHP has the functions json_encode and json_decode for this purpose.

datasage
  • 19,153
  • 2
  • 48
  • 54