treeSortable icon indicating copy to clipboard operation
treeSortable copied to clipboard

how do we get the result as json

Open VonalOrdu opened this issue 1 year ago • 2 comments

How can we call the result of our changes in json format?

VonalOrdu avatar Jul 09 '23 11:07 VonalOrdu

Hi, currently there is no way to get the updated JSON. This is not working with a data-driven approach instead the changes reflect the DOM level.

ahamed avatar Jul 19 '23 19:07 ahamed

But it's pretty easy to convert the DOM changes to JSON by adding code, check this example:

    // call it from reorder/level change event for example (and you could use it on the other event listeners)
    sortable.onSortCompleted(async (event, ui) => {
        await delay();
        var obj = FetchChild(); // get the object
        // Now you can send it via ajax to your server
        // [...]
        console.log(JSON.stringify(obj, null, 2)); // just print the output in console 
     });


    function FetchChild()
    {
     var data =[];
        // #sortable is your <ul> tag, change it
        $('#sortable > li').each(function(){
            data.push(buildJSON($(this)));
        });
        return data;
     }
    function buildJSON($li) 
    {
        var this_id = $li.attr("data-id");
        var parent_id = $li.attr("data-parent");
        var level = $li.attr("data-level");
        if (level == 1) { parent_id = 0; }
        var title = $li.find(".branch-title").html();
        var subObj = { "id": this_id, "parent_id": parent_id, "level": level, "title": title };
        $li.children('ul').children().each(function() {
            if (!subObj.children) { 
                subObj.children = [];
                }
            subObj.children.push(buildJSON($(this)));
        });
        return subObj;
    }

migrivas avatar Feb 15 '24 04:02 migrivas