Javascript – jstree : Uncaught TypeError: Cannot read property ‘children’ of undefined

ajaxjavascriptjqueryjstreejstree-search

In my server I am returning a JSON object in the format of jsTree :

{"id":"value", "text":"value", "parent":"value"} 

I am getting it in my view through an Ajax call. Console.log shows me the details but jsTree gives me the error:

Uncaught TypeError: Cannot read property 'children' of undefined

View:

$.ajax({
    url: "/category",
    dataType: 'json',
    type: 'GET',
    success: function (res) {
        $.each(res, function (i, obj) {
            products.push([obj.id, obj.parent, obj.text]);
            $('#jstree_demo_div').jstree({
                'core': {
                    'data': [{ "id": obj.id, "parent": obj.parent != 0 ? obj.parent : "#", "text": obj.text }]
                }
            });
            console.log(obj.parent != 0 ? obj.parent : "#");
        });

    }
});

Best Answer

I'm working with Ajax .

the problem I resolved it by declaring a new object javaScript that contains( id, parent, text)

exemple :

 var objJS = new Object(); 
 objJS .id = ObjectJason.id;
 objJS .parent = ObjectJason.parent!=="0" ?  ObjectJason.parent:"#";
 objJS .text = ObjectJason.text;

I declare an Array where I push all my objects and give it to 'data', like this

 $('#jstree_demo_div').jstree({
                'core': {
                    'data': Array ;
                }
            });

and it's working perfectly! I wish it will help a lot of people