Persistent drag and drop tree with jQuery, PHP and MySQL – part 2
In this second part of this article (this is the first part) i’m going to show you how to retreive and serialize the tree structure using jQuery and sent the serialized data to a php script (using ajax) that saves it on the database. In this way, we can have the persistence of any change made on the tree.
Let’s start with the serializzation problem, that is simply this: how can i retreive the structure of the tree in a form that can be sent to a php script via POST or GET? To do that i have to read every single branch of the tree and save, for every single category, three values: category_id, parent_id and orderby:
0:1:1|0:2:2|2:3:1|2:5:2|2:4:3|0:6:3|6:7:1|
The group category_id, parent_id and orderby are separated by a pipe. To do that we need a function that reads every single branch of the tree and it’s relative information. The function will call a php file to save the serialized in the mysql database.
This is the jQuery function that perform this operation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function(){ var serialStr = ""; var order = ""; $("ul.simpleTree li span").each(function(){ parentId = $(this).parent("li").parent("ul").parent("li").attr("id"); if (parentId == undefined) parentId = "root"; order = (($(this).parent("li").prevAll("li").size()+1))/2; if ( parentId != "root") serialStr += ""+parentId+":"+$(this).parent("li").attr("id")+":"+order+"|"; }); $.ajax({ type: "POST", url: "saveData.php", data: "serialized="+serialStr, success: function(msg){ $("#serializedList").html(msg); } }); return false; } |
Let me explain a bit how the jQuery function work: it loops through each span of the tree, read the current id of the li and the id of the parent li, and finally it calculates the position of the current element to use as orderby value in the category table.
When the string is created, i passed to a php script with an ajax call. The php file that saves the serialized data on the server is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | include_once("connection.php"); // the connection to the database if ($_POST['serialized']) { // create an array from the string $_POST['serialized'] // with the group category_id:parent_id:orderby for each array member // i strip the last pipe, so i will not have an array with a empty member at the end $categories = explode("|", substr($_POST['serialized'],0,-1)); $error = false; // loop through each array member foreach ($categories as $category) { // split the group by the colon and put the three value is separated variable list($parentId, $categoryId, $order) = split(":", $category); // update the database $result = mysql_query("UPDATE category SET parent_id = ".$parentId.", orderby = ".$order." WHERE category_id = ".$categoryId ) or die(mysql_error()); } echo "Tree updated."; } echo "<br />".$_POST['serialized']; |
The php is straight forward and i commented every step. The output of the php script is output inside a div called serializedList, so we can see the result of the operation. At the end of the script, i print also the serialized string to debug and test purpose.
You can see a working example of the tree at this page.
As you can see, the jQuery function is fired every time a branch is moved, thanks to the afterMove: callback of simpleTree.
In my real word applications, to create a new category and delete a category i use 2 small buttons, while to update a category i use the double click callback functionality of simpleTree. This is a how it looks: persistent tree final result.
If you are interested to know how i do it please let me know, i will be glad to help you
You can download all the scripts of this article here:
Please leave a comment if you like this article, thanks!
That’s all folks!
Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;) Tags: algorithm, how to, Javascript, jQuery, MySQL, PHP, tutorial, webdev
Bert
Very cool tutorial.
What i would like to know is how to drop the file-tree style and make a more table style catagory tree.
I would like to create a 100% width table that shows the catagories. within this table i would ike to drag and drop categories to any other category in the tree.
Thanks
Mauro
The markup is based on list now, but you can have a table look playing with the css of the simple-tree plugin.
In the future, maybe i will develop another version based on jQuery ui, that have a cool sortable feature that can be used with table too: http://jqueryui.com/demos/sortable/
Azam
How about the database?
Alex
Great Plugin. Thanks.
One question how do I enable linkable option for the tree. For example clicking on the menu name to open up a link to my edit page. I’ve added a href tag to the name, but clicking on it just selects the name and that’s it
Mauro
@Azam: You mean the categories table?
Mauro
@Alex: you can use the callback function for this:
$(document).ready(function(){
simpleTreeCollection = $('.simpleTree').simpleTree({
autoclose: true,
afterClick:function(node){
// your function on click
},
...
Let me know if you need more help…
ciao
Michel
Great plugin Mauro,
Just a question on the callback function. Where do I place this piece of code. I have tried to link the add and delete buttons with a href tag and a document.location tag but that didn’t work out. But a link on the $category['name'] seems like a more elegant solution.
Michel
I fixed it. I have made an onclick statement in the span and it works like a charm.
Hitesh Patel
Great plugin Mauro,
but i faced one problem, about the tree expandable & collapsable, when first time i come to the tree view, the whole tree open but the every parent node has (+) actually it should be (-) sign if the tree is open.
Please give me idea about this. And its great help to me.
Thank You.
Torsten
Hey Mauro,
I’m interessted to insert and delete categories. I would like a article-tree to insert/delete articles in my database.
You can write to me directly str34@yahoo.de
best regards
Torsten
Marco
Hi,
how can i do to add or remove an element?
Many thanks
Mauro
Here it is:
http://www.mdgart.com/2009/08/04/persistent-drag-and-drop-tree-with-jquery-php-and-mysql-crud/
Mauro
I posted today a new version with the basic CRUD funcionalities, enjoy
Mauro
Yes, i know, is a bug of simpleTree plugin. You can se autoclose: true to have the tree collapsed by default.
Marco
Many thanks
webnoobie
Nice tutorial Mauro!
so I want to use your script with modifying
Searching the whole net and this is what I want in my CMS.
I'm not this pro in Jquery
the categories names and add/delete.
Can you send me the script?
Thank you,
Frank
Mauro
You can download the script here:
You can find the script here: http://www.mdgart.com/2009/08/04/persistent-drag-and-drop-tree-with-jquery-php-and-mysql-crud/
Viagra
I am completly Agree with you! Great Article!