2

I am using asp.net and ajax to generate Json data.

When I am trying to draw tree using below code it's not working on other hand Code 2 section is working when I put it as static

Note: using library treant.js

link: http://fperucic.github.io/treant-js/

Code 1:

$(function () {
    $.ajax({
        type: "POST",
        url: "Default.aspx/Hello",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data)
        {
            var Details = data.d;          
            if (Details != "")
            {
                var tree_design = '';
                //sessionStorage.setItem("str_data", tree_design);

                var currDepth = 0;
                var totalData = $.map(Details, function (n, i) { return i; }).length;
                var lastNodeIndex = parseInt(totalData) - 2;
                //-----------------------------------------//
                $.each(Details, function (index, item)
                {
                    if (Details[parseInt(index) + 1] === undefined || Details[parseInt(index) + 1] == null || Details[parseInt(index) + 1] == "") 
                    { 
                        //alert("undefined");
                    }
                    else
                    {
                        //console.log(index);

                        //console.log(item.Name);
                        //console.log(item.Depth);
                        //alert(item.Depth);
                        //console.log(item.Lft);
                        //-----------------------------------//
                        // Level down? (or the first)
                        if (((parseInt(item.Depth) > parseInt(currDepth)) || parseInt(index) == 0) && parseInt(item.Depth) != 0) {
                            tree_design += 'children: [';
                        }
                        //----------------------------------//
                        // Level up?
                        if (parseInt(item.Depth) < parseInt(currDepth)) {
                            tree_design += '' + '}],'.repeat(parseInt(currDepth) - parseInt(item.Depth));
                        }
                        //----------------------------------//
                        if (parseInt(item.Depth) != 0)
                        {
                            tree_design += '{ connectors: { style: { stroke: "#000000" } },';
                        }
                        //---------Print Node Text-------------//
                        tree_design += 'text: { name: "' + item.Name + '" },HTMLclass: "blue",image: "images/no_member.png",';
                        //---------------------------------------//
                        //console.log(Details[parseInt(index) + 1].Depth);
                        var nextEleDepth = Details[parseInt(index) + 1].Depth;
                        //console.log(nextEleDepth);

                        // Check if there's chidren
                        if (parseInt(index) != lastNodeIndex && (parseInt(nextEleDepth) <= parseInt(item.Depth)))
                        {
                            tree_design += '},'; // If not, close the <li>
                        }
                        //---------------------------------------//
                        // Adjust current depth
                        currDepth = parseInt(item.Depth);
                        //---------------------------------------//
                        //console.log(parseInt(index)+"=="+lastNodeIndex);
                        // Are we finished?
                        if (parseInt(index) == lastNodeIndex) {
                            //console.log("Are we finished");
                            tree_design += '' + '}],'.repeat(currDepth);
                        }
                        //------------------------------------//
                    }
                });
                //------------------Draw Tree---------------------------//
                //console.log(tree_design);

                var chart_config = {
                    chart: {
                        container: "#basic-example",
                        nodeAlign: "BOTTOM",
                        connectors: {
                            type: "step"
                        },
                        node: {
                            HTMLclass: "nodeExample1"
                        }
                    },
                    nodeStructure: {
                        tree_design
                    }
                };

                //console.log(tree_design);

                new Treant(chart_config);
                //-------------------------------------------------------//
            }
        }
    });
});

Code 2: Working

     $(function () {
    $.ajax({
        type: "POST",
        url: "Default.aspx/Hello",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data)
        {
            var Details = data.d;          
            if (Details != "")
            {
                var tree_design = '';
                //sessionStorage.setItem("str_data", tree_design);

                var currDepth = 0;
                var totalData = $.map(Details, function (n, i) { return i; }).length;
                var lastNodeIndex = parseInt(totalData) - 2;
                //-----------------------------------------//
                $.each(Details, function (index, item)
                {
                    if (Details[parseInt(index) + 1] === undefined || Details[parseInt(index) + 1] == null || Details[parseInt(index) + 1] == "") 
                    { 
                        //alert("undefined");
                    }
                    else
                    {
                        //console.log(index);

                        //console.log(item.Name);
                        //console.log(item.Depth);
                        //alert(item.Depth);
                        //console.log(item.Lft);
                        //-----------------------------------//
                        // Level down? (or the first)
                        if (((parseInt(item.Depth) > parseInt(currDepth)) || parseInt(index) == 0) && parseInt(item.Depth) != 0) {
                            tree_design += 'children: [';
                        }
                        //----------------------------------//
                        // Level up?
                        if (parseInt(item.Depth) < parseInt(currDepth)) {
                            tree_design += '' + '}],'.repeat(parseInt(currDepth) - parseInt(item.Depth));
                        }
                        //----------------------------------//
                        if (parseInt(item.Depth) != 0)
                        {
                            tree_design += '{ connectors: { style: { stroke: "#000000" } },';
                        }
                        //---------Print Node Text-------------//
                        tree_design += 'text: { name: "' + item.Name + '" },HTMLclass: "blue",image: "images/no_member.png",';
                        //---------------------------------------//
                        //console.log(Details[parseInt(index) + 1].Depth);
                        var nextEleDepth = Details[parseInt(index) + 1].Depth;
                        //console.log(nextEleDepth);

                        // Check if there's chidren
                        if (parseInt(index) != lastNodeIndex && (parseInt(nextEleDepth) <= parseInt(item.Depth)))
                        {
                            tree_design += '},'; // If not, close the <li>
                        }
                        //---------------------------------------//
                        // Adjust current depth
                        currDepth = parseInt(item.Depth);
                        //---------------------------------------//
                        //console.log(parseInt(index)+"=="+lastNodeIndex);
                        // Are we finished?
                        if (parseInt(index) == lastNodeIndex) {
                            //console.log("Are we finished");
                            tree_design += '' + '}],'.repeat(currDepth);
                        }
                        //------------------------------------//
                    }
                });
                //------------------Draw Tree---------------------------//
                //console.log(tree_design);

                var chart_config = {
                    chart: {
                        container: "#basic-example",
                        nodeAlign: "BOTTOM",
                        connectors: {
                            type: "step"
                        },
                        node: {
                            HTMLclass: "nodeExample1"
                        }
                    },
                    nodeStructure: {
                        text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]
                    }
                };

                //console.log(tree_design);

                new Treant(chart_config);
                //-------------------------------------------------------//
            }
        }
    });
}); 

Code-3: Server Scripting (ASP.Net C#)

using CDB.System.Common.Layout.Company;
using PRP.PPL.System.include.config.connection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PPL.Data.HRD.Organogram.Tree1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static Details[] Hello()
        {
            string sql;
            db_ppl Connstring = new db_ppl();
            sql = @"SELECT        node.category_id, node.name, COUNT(parent.category_id) - 1 AS depth, node.lft, node.rgt
                   FROM            nested_category AS node CROSS JOIN
                                            nested_category AS parent
                   WHERE        (node.lft BETWEEN parent.lft AND parent.rgt)
                   GROUP BY node.category_id, node.name, node.lft, node.rgt
                    ORDER BY node.lft";
            List<Details> details_data = new List<Details>();

            using (SqlConnection con = Connstring.getcon)
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        Details col_data = new Details();
                        col_data.category_id = reader.GetInt32(0);
                        col_data.Name = reader.GetString(1);
                        col_data.Depth = reader.GetInt32(2);
                        col_data.Lft = reader.GetInt32(3);
                        col_data.Rgt = reader.GetInt32(4);                       
                        details_data.Add(col_data);
                    }
                }
            }

            return details_data.ToArray();
        }

        //---------------For Details Data----------------//
        public class Details
        {
            public Int32 category_id { get; set; }
            public string Name { get; set; }
            public Int32 Depth { get; set; }
            public Int32 Lft { get; set; }
            public Int32 Rgt { get; set; }           

        }
    }
}

Code-4: asp.Net Part

<%@ Page Title="" Language="C#" MasterPageFile="~/CDB/System/Common/Layout/Master/Panel.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="PPL.Data.HRD.Organogram.Tree1._default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
    #basic-example
    {
        overflow: unset !important;
    }
</style>
<link href="../../../../../CDB/System/Assets/plugins/Organogram/Treant.css" rel="stylesheet" />
<link href="../../../../../CDB/System/Assets/plugins/Organogram/basic-example.css" rel="stylesheet" />

<script src="../../../../../CDB/System/Assets/plugins/Organogram/raphael.js"></script>
<script src="../../../../../CDB/System/Assets/plugins/Organogram/Treant.js"></script>

<script src="default.js"></script>
<div class="content-wrapper" style="padding:0;margin:0;">
    <!-- Main content -->
    <section class="content">
        <div class="row">           
            <!-- left column -->
            <div class="col-md-12">
                <!-- general form elements -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">Book Progress</h3>
                    </div>
                    <!-- /.box-header -->
                    <div class="box-body">

                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-group" style="overflow:scroll;">
                                    <div class="chart" id="basic-example"></div>
                                </div>
                            </div>
                        </div>
                        <div class="box-footer">

                        </div>                                                                                              
                    </div>                       
                </div>
                <!-- /.box -->
            </div>
        </div>
    </section>
 </div>
</asp:Content>

Output : enter image description here

2 Answers 2

2
var tree_design='text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; 



 nodeStructure: {                       
    tree_design
}

when you link tree_design in nodeStructure it's in string format but nodeStructure expect in json format either convert tree_design in json or do this way

var tree_design='{ name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; 

nodeStructure: {                       
    text: tree_design
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your reply. please check my php and asp.net code which is given below code is working in php but i want to do it in asp.net
1

I have solution in PHP code is given below now, I want to convert it to asp.net by using Ajax and jQuery

<?php
    include('../../connection/connection.php');
    error_reporting(0);

    //--------------Tree Design---------------//
    $sql_tree = "SELECT node.category_id,node.`name` AS Name, (COUNT( parent.`category_id` ) -1) AS depth,node.`lft`,node.`rgt`,
IFNULL((SELECT `category_id` 
           FROM `nested_category` t2 
           WHERE t2.lft < node.lft AND t2.rgt > node.rgt    
           ORDER BY t2.rgt-node.rgt ASC LIMIT 1 ),0) AS parent_id  
     FROM `nested_category` AS node
            CROSS JOIN `nested_category` AS parent
                WHERE node.`lft` BETWEEN parent.`lft`
                    AND parent.`rgt`
            GROUP BY node.`name`
            ORDER BY node.`lft`";

    $qry_tree = mysqli_query($con,$sql_tree);

    $array_parent_data = array();

    // Build array
    $tree = array();
    while($fetch_tree=$qry_tree->fetch_assoc())
    {
        $tree[] = $fetch_tree;
    }

    // Bootstrap loop
    $tree_design        = '';
    $currDepth     = 0; 
    $lastNodeIndex = count($tree) - 1;
    $parent_id="";

    // Start the loop
    foreach ($tree as $index => $currNode) 
    {
        $lr_distance=$currNode['rgt']-$currNode['lft'];

        $sql_path_height="SELECT * FROM `tree_details` WHERE `tree_id`=".$currNode['category_id'];
        $qry_path_height = mysqli_query($con,$sql_path_height);
        $fetch_path_height=$qry_path_height->fetch_assoc();
        $path_height=$fetch_path_height['level_height'];
        $path_height=($path_height=="")?0:$path_height;
        $level_change=($path_height/10);

        //-----------------------------------//
        // Level down? (or the first)
        //if (($currNode['depth'] > $currDepth || $index == 0) && $currNode['depth']!=0) {
        if (($currNode['depth'] > $currDepth) && $currNode['depth']!=0) {
            $tree_design .= 'children: [';
        }

        // Level up?
        if ($currNode['depth'] < $currDepth) {
            $tree_design .= str_repeat(']},', $currDepth - $currNode['depth']);
        } 

        // Always open a node
        $t = ($index == 0) ? 1 : 2;

        if($currNode['depth']!=0)
        {
            $tree_design .= '{
                                connectors: {
                                    style: {
                                        stroke: "#000000"
                                    }
                            },';
        }
        //--------------For Leaf--------------//        
        if($path_height>0 && $lr_distance==1)
        {
            for($i=0;$i<$level_change;$i++)
            {
                $tree_design.='pseudo: true,
                    connectors: {
                        style: {
                            stroke: "#000000"
                        }
                    },
                    children: [
                    {'; 
            }   
        }
        //-----------For Parent---------------//
        if($path_height>0 && $lr_distance>1)
        //if($lr_distance>1)
        { 
            $sql_all_child="SELECT * FROM `nested_category` WHERE `lft`>".$currNode['lft']." AND `rgt`<".$currNode['rgt'];
            $qry_all_child = mysqli_query($con,$sql_all_child);
            $all_child_list="";
            while($fetch_all_child=$qry_all_child->fetch_assoc())
            {
                $all_child_list.= ",".$fetch_all_child['category_id'].",";
            }
            //$all_child_list = str_replace(",,",',',$all_child_list);

            $array_parent_data[]=$currNode['category_id']."#".$path_height."|".$all_child_list;
            $array_parent_data=array_reverse($array_parent_data);

            for($i=0;$i<$level_change;$i++)
            {
                $tree_design.='pseudo: true,
                    connectors: {
                        style: {
                            stroke: "#000000"
                        }
                    },
                    children: [
                    {'; 
            }   
        }
        //---------Print Node Text-------------//
        $tree_design .= 'text: { name: "'.trim($currNode['Name']).'" },HTMLclass: "blue",image: "images/no_member.png",';
        //---------Close Leaf Brackets---------//
        if($path_height>0 && $lr_distance==1)
        {
            for($i=0;$i<$level_change;$i++)
            {
                $tree_design.='}]'; 
            }   
        }
        //---------Close Parent Brackets---------//
        foreach($array_parent_data as $key => $parent_data)
        {
            $tmp_parent=explode("#",$parent_data);
            $tmp_parent_id=$tmp_parent[0];
            //echo $tmp_parent_id."<<>>".$currNode['parent_id']."<br>";

            //if($tmp_parent_id==$currNode['parent_id'])
            {
                $array_parent_data[$key] = str_replace(",".$currNode['category_id'].",",'',$parent_data);
                $check_child_list=explode("|",$array_parent_data[$key]);
                $parent_details = explode("#",$check_child_list[0]);
                $close_parent_id = $parent_details[0];

                //if($close_parent_id==$currNode['parent_id'] && empty($check_child_list[1]))
                if(empty($check_child_list[1]))
                {
                    //echo $tmp_parent_id."<<>>".$currNode['parent_id']."<br>";

                    $close_parent_height = $parent_details[1];
                    $close_parent_height=($close_parent_height=="")?0:$close_parent_height;
                    $level_change_parent = $close_parent_height/10;

                    //echo $close_parent_id."|".$close_parent_height."<br>";

                    for($i=0;$i<$level_change_parent;$i++)
                    {
                        $tree_design.='}],';    
                    } 
                    unset($array_parent_data[$key]);
                }
            }
        }
        //print_r($array_parent_data);
        //---------------------------------------//

        // Check if there's chidren
        if ($index != $lastNodeIndex && $tree[$index + 1]['depth'] <= $tree[$index]['depth']) {
            $tree_design .= '},'; // If not, close the <li>
        }

        // Adjust current depth
        $currDepth = $currNode['depth'];

        // Are we finished?
        if ($index == $lastNodeIndex) {
            $tree_design .= '' . str_repeat('}],', $currDepth);
        }
    } //End Loop
//-----------------------------------------------------//
?>

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    <title> Tree </title>
    <link rel="stylesheet" href="Treant.css">
    <link rel="stylesheet" href="basic-example.css">
    <style type="text/css">
        #basic-example
        {
            overflow: unset !important;
        }
    </style>
</head>
<body>
    <div class="chart" id="basic-example"></div>
    <script src="jquery-1.10.2.js"></script>
    <script src="raphael.js"></script>
    <script src="Treant.js?id=<?php echo rand(); ?>"></script>

    <!--<script src="basic-example.js"></script>-->

    <script>
        var chart_config = {
            chart: {
                container: "#basic-example",

                nodeAlign: "BOTTOM",

                connectors: {
                    type: "step"
                },
                node: {
                    HTMLclass: "nodeExample1"
                }
            },
            nodeStructure: {
                //---------------------------------------------//
                <?php echo $tree_design; ?>
                //text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Chairman)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",}],             
                //---------------------------------------------//
            }
        };

        new Treant( chart_config );


  </script>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.