Question

I'm using Dynatree for the first time and wrote a PHP script that returns a properly formatted JSON array.

I've read the Dynatree documentation, but can't figure out how to pass in the JSON array from my PHP script so its contents can be loaded as the tree structure.

At the top of my HTML file, I'm using <?php include('tree.php') ?> which automatically returns the formatted JSON array (named $categories). I'd also be fine with calling a function from JavaScript to retrieve the tree if that makes it easier.

Can someone show me how to deliver my array to Dynatree?

Was it helpful?

Solution

You can use a data- attribute, like this:

<?php
$dynaConfig = array('children'=>array(
    array('title' => 'Alice'), 
    array('title' => 'Bob')
));
$dynaConfigJSON = json_encode($dynaConfig);

// HTML head goes here
echo '<div id="tree" data-dyna="' . htmlspecialchars($dynaConfigJSON) . '">';
?>

<script>
$(function() {
   var dtConfig = $.parseJSON($('#tree').attr('data-dyna'));
   $('#tree').dynatree(dtConfig);
});

Here's a live example, and the corresponding full source code.

OTHER TIPS

You can also separate the code of php in a file like tree.php and then call it in javascript.

<div id="tree">  </div>
<script type="text/javascript">
  $(function(){
    $("#tree").dynatree({
      initAjax: {
        url: "tree.php"
        }
      }
    }
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top