Jump to content

Php Object to Javascript Object?


cgishack

Recommended Posts

Is there a way to convert a Php object to a JavaScript Object onn client side ?

 

I tried using JSON

$output = json_encode($Obj);
echo $output."\n";

 

But I got a slight error,

Warning: [json] (json_encode_r) type is unsupported, encoded as null. in 

 

whats the best way I should do this ?

 

Drew

Link to comment
https://forums.phpfreaks.com/topic/52082-php-object-to-javascript-object/
Share on other sites

try

<?php
class mytest 
{
    public $x;
    public $y;
    public $z;
    
    function __construct ($a, $b, $c)
    {
        $this->x = $a;
        $this->y = $b;
        $this->z = $c;
    }
    
    function make_js_obj ()
    {
        /**
        * write js code to create object with vars
        */
        $classname = get_class($this);
        echo "\nfunction $classname()\n";
        echo "{\n";
        $cvars = get_object_vars($this);
        foreach ($cvars as $k=>$v)
        {
            echo "\tthis.$k = $v\n";
        }
        echo "}\n\n";
    }
}


?>
<html>
<head>
<meta name="generator" content="PhpED Version 4.5 (Build 4513)">
<title>Sample</title>
<meta name="author" content="Barand">
<script>
        <?php 
          $obj = new mytest(1,2,3);
          $obj->make_js_obj();
        ?>
        
        function test_the_object()
        {
            jso = new mytest()
            document.write(jso.x + "<br>" + jso.y + "<br>" + jso.z)
        }
</script>
</head>
<body onload="test_the_object()">

</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.