You are here

Example of jsTree with lazy loading and AJAX call

Submitted by Asif Nowaj, Last Modified on 2019-11-08

When you tree data grows large and large enough that loading whole tree data is too much heavy and time consuming, then your best choice would be to use lazy load. Lazy loading means only immediate child nodes will be loaded on the fly whenever user clicks on a node that has children.

In this scenario, jsTree will perform the ajax requests as user browses the tree. Below example will depict lazy loading with jsTree and AJAX call. You can go through this example to understand how dynamically loads data with ajax call. In this example, an existing data source URL has been used from jsTree but you can use your own WebAPI or MVC url to get the data securely.

In the below example, the initial ajax URL would be https://www.jstree.com/fiddle/?lazy
So the initial data that would be returned as below

[{"id":1,"text":"Root node","children":[{"id":2,"text":"Child node 1","children":true},{"id":3,"text":"Child node 2"}]}]

Hence there would be two child nodes loaded initialy. Where only "Child node 1" has children. Now when you will click on "Child node 1", data function will return node id that is 2 and ajax URL would form as https://www.jstree.com/fiddle/?lazy&id=2

This URL will return the data as below:

["Child node 3","Child node 4"]

The complete code will look like


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Simple jsTree using ajax and load nodes on demand</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css" />
	<script src="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js"></script>
    <script type="text/javascript">
        $(function () {
			$('#SimpleJSTree').jstree({
				'core' : {
					'data' : {
						'url' : "https://www.jstree.com/fiddle/?lazy", 
						'data' : function (node) { 
							return { 'id' : node.id }; 
						} 
					} 
				} 
			});
        });
    </script>
</head>
<body>
    <div id="SimpleJSTree"></div>
</body>
</html>

Discussion or Comment

If you have anything in mind to share, please bring it in the discussion forum here.

https://forum.everyething.com/jstree-f33/