Jump to content

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>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.