Category: Javascript

How to Pass an Object from PHP to Javascript and Back Again Using JSON

Many time you need to pass a PHP object through javascript to PHP . JSON and a some PHP and Javascript functions make that easy!

1st let me create a php object.

<?php $cms = array('java'=>'OpenCms', 'php'=>'wordpress', 'python'=>'django', 'c++'=>'CppCMS') ?>

Now assign this object to a javascript variable.

var obj = JSON.parse('<?php echo json_encode($cms) ?>');

So. the object  is now on a javascript variable. Now I can pass the Javascript Object through Ajax or several other ways:

I am showing ajax here:

// <![CDATA[
function loadpage() {

var obj = JSON.parse('');

        type: "GET",
        url: "your ajax url",
        data: { obj: obj
        },        success: function(html){
// ]]>

In my PHP(on ajax page) script, I now need to translate the JSON to a php object again:

$obj = $_GET['obj']; 
$obj = json_decode(json_encode($obj), FALSE);