generating a dynamic tree structure with JSON by leveraging a database

It was brought to my attention that I am facing a unique challenge: I am trying to generate a JSON tree using Java/JavaScript with data sourced from a MySQL Database. I have not been able to locate the appropriate documentation for this task Any assistance in sorting out these issues would be greatly appreciated. Thank you in advance for your help.

Answer №1

To connect to the MySql database and display the data to the client, you will require a server-side language.

Here is a simple example:

Using PHP (getJSON.php)

$db = new mysqli('localhost', 'user', 'pass', 'demo');

$strSQL = mysqli_query("SELECT ...");
$result = $db->query($sql)
$rows = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
         $rows[] = $row;
    }
}

$db->close()
print json_encode($rows);

For Javascript/jQuery:

$.ajax({
   url: 'http://{your-host}/getJSON.php',
   dataType: 'JSON',

   success: function(data, status) {
        console.log(data)
   },
   error: function(e) {
       console.log(e.statusText + " : " + e.responseText);
   }
});

This code has not been tested, but it should work as described :)

Answer №2

https://i.sstatic.net/fc2MA.jpg

I find obtaining tree objects in Java to be quite challenging. I attempted it myself and found another approach. By clicking on a folder, you can access the files or subfolders within. In this case, I utilized the Dropbox API for this purpose. Feel free to gather inspiration from it and explore your own ideas.

treeview.html:

<!-- Nested list template -->
              <script type="text/ng-template" id="items_renderer.html">
                <div ui-tree-handle>
                <span ng-show="item.file" class="glyphicon glyphicon-folder-close"></span>
                  <a ng-hide="item.file" class="btn btn-success btn-xs" data-nodrag ng-click="toggle(this);toggleMe(this)">
                  <span class="glyphicon glyphicon-folder-close" ng-class="{'glyphicon-chevron-right': collapsed, 'glyphicon-chevron-down': !collapsed}">
                  </span></a>
                  {{item.title}}
                  <a class="pull-right btn btn-danger btn-xs" data-nodrag ng-click="remove(this)"><span class="glyphicon glyphicon-remove"></span></a>
                  <a class="pull-right btn btn-primary btn-xs" data-nodrag ng-click="newSubItem(this)" style="margin-right: 8px;"><span class="glyphicon glyphicon-plus"></span></a>
                </div>
                <ol ui-tree-nodes="options" ng-model="item.items" ng-class="{hidden: collapsed}">
                  <li ng-repeat="item in item.items" collapsed="true" ui-tree-node ng-include="'items_renderer.html'">
                  </li>
                </ol>
              </script>

              <div ui-tree="options">
                <ol ui-tree-nodes ng-model="list" >
                  <li ng-repeat="item in list track by $index"  ui-tree-node collapsed="true" ng-include="'items_renderer.html'"></li>
                </ol>
              </div>

            </div>

          </div>

        </div>

      </div>
    </div>

treecontroller.js:

app.controller('treeController',['$scope', '$http','fileUpload', function($scope, $http,fileUpload) {

    console.log("$$$ tree controller has been initialized $$$")

    /** To get list of files from the Dropbox */
    var files = [];
    $scope.list = [];
    var foldername = '';
    /***  Call the Dropbox cloud to retrieve files and folders for initialization*/

    $scope.getListOfFiles = function() {
        var foldername = "/";
        $http.get("http://localhost:8080/dropbox_api_.10/dropbox/getListOfFiles/?folderPath=" + foldername)
        .success(function(data, status) {
            console.log("List of files from Dropbox folder:", angular.toJson(data));
            $scope.list = data;
        }).error(function(data, status, headers, config) {
            alert('Error');
        });
    }

    var folders = [];
    var buildFolderPath = function(scope) {
        if (scope.$parentNodeScope != null) {
            folders.push(scope.$parentNodeScope.$modelValue.title);
            buildFolderPath(scope.$parentNodeScope);
        }
    };

    /** Expand tree upon click, collapse when needed*/
    $scope.toggleMe = function(scope) {
        folders = [];
        foldername="";
        if (!scope.collapsed) {
            var nodeData = scope.$modelValue;
            folders.push(nodeData.title);
            buildFolderPath(scope);
            console.log(angular.toJson(folders));

            for (var i = folders.length - 1; i >= 0; i--) {
                foldername += "/" + folders[i];
            }

            $http.get("http://localhost:8080/dropbox_api_.10/dropbox/getListOfFiles/?folderPath=" + foldername)
            .success(function(data, status) {
                console.log("Selected path:", foldername);
                console.log("List of files from Dropbox folder:", angular.toJson(data));
                for (var i = 0; i < data.length; i++) {
                    nodeData.items.push(data[i]);
                }
            }).error(function(data, status, headers, config) {
                alert('Error');
            });
        }
        else{
            var nodeData = scope.$modelValue;
            nodeData.items = [];

        }
    };



    $scope.getListOfFiles();
    /*****************/

    $scope.remove = function(scope) {
        scope.remove();
    };

    $scope.toggle = function(scope) {
        scope.toggle();
    };

    $scope.newSubItem = function(scope) {
        var nodeData = scope.$modelValue;
        nodeData.items.push({
            id : nodeData.id * 10 + nodeData.items.length,
            title : nodeData.title + '.' + (nodeData.items.length + 1),
            items : []
    });
    };
}]);

java:

public ArrayList<String> listDropboxFolders(@RequestParam("folderPath") String folderPath) throws DbxException {

        ArrayList<String> fileList=new ArrayList<String>();
        for (DbxEntry child : listing.children) {
            //File child;
            if(child.isFolder()){
                fileList.add(child.name);
                System.out.println("File is present: "+child.name);
            }else{
                System.out.println("File name: "+child.name);
            }
            child.toString());
        }
        return fileList;    
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why must the sidebar be displayed horizontally on the smartphone screen?

I've been struggling to make the sidebar menu on my smartphone display horizontally with icons at the top and text at the bottom. I've tried using flex and other methods, but it still doesn't work sideways. Am I missing something? const s ...

Reorganizing elements within an array using a foreach loop

Currently, I am tackling the Facebook Graph API, which provides me with a JSON array response. However, I find myself needing to reformat the JSON as I am not entirely comfortable with their format. Here is an example of my JSON response: "ids": [ { ...

Interruption of Java Server Socket: A Comprehensive Guide

Is there a way to gracefully stop a server socket that is listening for clients? Here's an example of my code: private ServerSocket serverSocket; class ServerThread implements Runnable { private BufferedReader input; public void run() ...

JQuery user interface dialog button

When using a jQuery UI dialog, I want to add tooltips to buttons. In my current code: buttons: { 'My Button' : function(e) { $(e.target).mouseover(function() { alert('test'); }); } This code triggers an action only a ...

Change prompt-sync from require to import syntax

In my Node project, I have integrated the prompt-sync module. const prompt = require('prompt-sync')(); const result = prompt(message); To maintain consistency in my TypeScript code, I decided to switch from using require to import. In order to ...

NodeJS - session information lost after building ReactJavaScript application

I've created a NodeJS web application with basic functionality for user login and pulling data from MySql based on session information. The app is functioning as intended (Link). However, when I implement the client-side in React, the session data is ...

Tips for showcasing several images with accompanying content once the webpage has finished loading

I am faced with an issue on my PHP website. The website is a social networking platform with numerous images and contents. I am seeking a way to first display only the content to the user, then show the images after they have all finished loading. Addition ...

Ways to modify the attribute of an element in an ImmutableList({}) nested within Immutable.Map({})

Is there a way to modify the property of an item within an ImmutableList({}) that is nested inside an Immutable.Map({})? This is my current setup: const initialState = Immutable.Map({ width: window.board.width, height: window.board.height, li ...

Can the HTML attributes produced by AngularJS be concealed from view?

Is there a way to hide the Angular-generated attributes such as ng-app and ng-init in the HTML code that is output? I want to present a cleaner version of the HTML to the user. Currently, I am using ng-init to populate data received from the server, but ...

Babel continues to encounter issues with async/await syntax, even with all the necessary presets and plugins installed

I am encountering a compiler error while attempting to compile an async/await function using Babel. Below is the function in question: async function login(username, password) { try { const response = await request .post("/api/login") . ...

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

Encountering NoSuchMethodError when attempting to save data with Morphia to DataStore

Today, I decided to give Morphia for MongoDB ORM a try. In the past, we have always used the mongo-java-driver directly for CRUD operations, but ORM seems like a more logical choice. Our current version of mongo-java-driver is 3.1.0, and I am using Morphi ...

Dealing with various methods of null representation in serde

Developing a client library for a REST server known as Octoprint (used to manage 3D printers) is my current project. One of the specific types I am focusing on is shown below: #[derive(Serialize, Deserialize, Debug)] pub struct JobInfo { /// The file ...

Encountering an issue with the autocomplete feature in the jQuery library where it is stating "this.source is not a function."

Here's the code snippet I'm working with: $.ajax({ type: "GET", url: "https://url.com", dataType: "json", success: function (data) { $("#search").autocomplete({ source: data, select: function (even ...

Show PDF within the browser using ajax technology

I've come across this question multiple times in various forms, but I still can't seem to find a satisfactory answer. When using the mpdf library to generate PDFs, I send some hidden field data to a PHP script via ajax. Below are snippets of the ...

Exploring the capabilities of JavaScript on the iOS platform

Here is the code I've written for my iOS application: webView = [[UIWebView alloc] init]; webView.delegate = self; [webView loadHTMLString:@"<script type=\"text/javascript\" src=\"myFile.js\"></script& ...

The step-by-step guide to testing an Angular promise using Jasmine

An issue arises when attempting to test the code below using Jasmine, as the console.log in `then` is never called. The question remains: is this problem related to Angular or Jasmine? describe("angular test", function() { var $q; ...

AngularJS - Not binding $scope to the DOM

Recently starting out with Angular, I decided to practice by creating a simple website. One of the features I want to include is displaying the number of times a button has been clicked through data binding. Here's the controller code I've writte ...

Javascript malfunctioning - exhausted all troubleshooting options

My JavaScript code consists of a single line, but I keep encountering the "getElementById null" error. document.getElementById("menu-background").style.left = "0"; HTML: <html> <head> <title></title> <link rel="style ...

Creating a Commentary System in VueJS Similar to Medium

One feature that I admire in Medium is their commenting interface, which allows users to highlight specific portions of an article and leave comments. I am interested in integrating a similar commenting feature into a VueJS application. While researching ...