1

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?

cantera
  • 24,479
  • 25
  • 95
  • 138

2 Answers2

3

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • Thanks for responding. Your solution works, but my tree displays "null" because my array uses id values for its keys and apparently this is a problem for Dynatree. Have you run into this before and is there a fix that you know of? – cantera Mar 25 '12 at 09:19
  • Updated the answer with a live example (which works fine on my system) and source code. Can you post a link to your full site/source code? – phihag Mar 25 '12 at 11:58
  • Answer accepted - thanks for all your help. In case anyone else encounters this, Dynatree apparently requires every node in the 'children' array to have sequential key values starting with 0. I was using node id's for sub-array index values, which is what led to my problem. – cantera Mar 27 '12 at 04:21
2

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>