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.

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

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() {

jQuery.noConflict();
var obj = JSON.parse('');
jQuery('#xxx').text('Loading...');    

jQuery.ajax({
        type: "GET",
        url: "your ajax url",
        data: { obj: obj
        },        success: function(html){
             jQuery('#xxx').html(html);
           }});
}
// ]]>

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

<?php 
$obj = $_GET['obj']; 
$obj = json_decode(json_encode($obj), FALSE);
 ?>
Advertisements