DRAG AND DROP NESTABLE MENU ON PHP AND MYSQL AND JQUERY

http://jumnuoy.blogspot.com/2015/03/drag-and-drop-nestable-menu-on-php-and.html

Catching backend development, each programmer is faced with the fact that any tree structure - whether it be a menu or list of categories you want displayed on the site are not the usual drop-down list, and beautifully decorated, that user would be convenient to use your CMS! You can nicely formatted output blocks, indenting child partitions, but streamlined sections will still not comfortable. In support comes powerful jQuery plugin Nestable.

Nestable download it, please visit the developer http://dbushell.github.io/Nestable/
Now let's create the menu tree sorted drag and drop: 
The database will have a standard structure. id, name, parent_id and cell sorting order for the values.

So take a sample of all parent categories and put the results into an array:


$ Sql = " SELECT * FROM menu WHERE parent_id = '0'  ORDER  BY  order ";
$ Result = mysql_query ($ sql, $ connection);
$ NumRows = mysql_num_rows ($ result);



Now we derive the page block with parent elements
echo  "<div class = 'cf-nestable Lists'> \ n" ;
  echo  "<div class = 'dd' ID = 'nestableMenu'> \ n \ n" ;
   echo  "<ol class = 'dd-list'> \ n " ;  
    while ( $ row = mysql_fetch_array ( $ result )) {
     echo  "\ n" ;    
     echo  "<li class = 'dd-Item' Data-ID = '{$ row [' ID ']}'>" ;
     echo  "<div class = 'dd-handle'> {$ row ['ID']}: {$ row ['name']} </ div>" ;
    menu_showNested ( $ row [ 'ID' ]);    
     echo  "</ li> \ n" ;
   }   
  echo  "</ ol> \ n \ n" ;
  echo  "</ div> \ n" ;
 echo  "</ div> \ n \ n" ;
  
// The unit must be here, do not move it 
echo  "<div ID = 'sortDBfeedback' style = 'border: 1px solid #eaeaea; padding: 10px; margin: 15px;'> </ div> \ n" ;

Perhaps you have noticed function menu_showNested? Now we will use a recursive function to display all child categories.


function  menu_showNested ( $ parentID )  {
  $ sql = "SELECT * FROM WHERE parent_id menu = '$ parentID' ORDER BY order" ;
  $ result = mysql_query ( $ sql , $ connection );
  $ numRows = mysql_num_rows ( $ result );
 
 if ( $ numRows > 0 ) {
   echo  "\ n" ;
   echo  "<ol class = 'dd-list'> \ n" ;
    while ( $ row = mysql_fetch_array ( $ result )) {
     echo  "\ n" ;    
     echo  " <li class = 'dd-Item' Data-ID = '{$ row [' ID ']}'> \ n " ;
      echo  "<div class = 'dd-handle'> {$ row ['ID']} : {$ row ['name']} </ div> \ n " ;
     menu_showNested ( $ row [ 'ID' ]);    
     echo  "</ li> \ n" ;
   }
  echo  "</ ol> \ n" ;
 }
}
All menus we derived.

Now the hardest part - the creation and transfer of the array in the format json handler on the server and save the data in the database

// ========================================== Nestable script 
function  lagXHRobjekt ()  {
     var XHRobjekt = null ;
     try {
        ajaxRequest = new XMLHttpRequest (); // Firefox, Opera, ... 
    } catch (Err1) {
         try {
            ajaxRequest = new ActiveXObject ( "Microsoft.XMLHTTP" ); // Noen IE v. 
        } catch (ERR2) {
             try {
                ajaxRequest = new ActiveXObject ( "Msxml2.XMLHTTP" ); // Noen IE v. 
            } catch (ERR3) {
                ajaxRequest = false ;
            }
        }
    }
    Return ajaxRequest;
}

// Function to send by post to the order of the array in json format 
function  menu_updatesort (jsonstring)  {
    mittXHRobjekt = lagXHRobjekt ();
    if (mittXHRobjekt) {
        mittXHRobjekt.onreadystatechange = function ()  {
             if (ajaxRequest.readyState == 4 ) {
                 var = ajaxDisplay document .getElementById ( 'sortDBfeedback' );
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            } else {
                 // comment out this line if you do not want to display the spinner download 
                document .getElementById ( 'sortDBfeedback' ) .innerHTML = "<img style = 'height: 11px;' src = '/ Themes / admin / Images / loading.gif' alt = 'ajax-loader' /> " ;
            }
        }
        var tosend = "jsonstring =" + jsonstring;
        ajaxRequest.open ( "POST" , "/ admin / menu / menu_sortable_save /" , True );
        ajaxRequest.setRequestHeader ( "Content-type" , "Application / x-www-form-urlencoded" );
        ajaxRequest.send (tosend);
    }
}

$ ( document ) .ready ( function ()
 {
     // update function menu items 
    var updateOutput = function (e)
     {
         var list = e.length? e: $ (e.target),
            output = list.data ( 'output' );
         if ( window .json) {
            output.val ( window .JSON.stringify (list.nestable ( 'serialize' ))); //, null, 2)); 
            menu_updatesort ( window .JSON.stringify (list.nestable ( 'serialize' )));
        } else {
            output.val ( 'JSON Browser support required for this Demo.' );
        }
    };

    // Call the function to change the order of menu entries in the database. 
    $ ( '#nestableMenu' ) .nestable ({Group: 1 }). on ( 'Change' , updateOutput);

    // Output the initial sequence if the item exists on the page 
    var variable = $ ( '#nestableMenu' ) .data ();
     if ( typeof variable! == "undefined" && variable) {
        updateOutput ($ ( '#nestableMenu' ) .data ( 'output' , $ ( '# nestableMenu-output' )));
    }

    // Button to deploy svetnut menu 
    $ ( '# nestable-menu' ) .on ( 'Click' , function (e)
     {
         var target = $ (e.target),
            Action = target.data ( 'Action' );
         if (Action === 'Expand-All' ) {
            $ ( '.dd' ) .nestable ( 'ExpandAll' );
        }
        if (Action === 'Collapse-All' ) {
            $ ( '.dd' ) .nestable ( 'CollapseAll' );
        }
    });

    // Fix allows you to click on links in nestable 
    $ ( ".dd A" ) .on ( "mousedown" , function (Event)  { // Prevent mousedown nestable Click
        event.preventDefault ();
        Return  false ;
    });
    $ ( ".dd A" ) .on ( "Click" , function (Event)  { // Event Click
        event.preventDefault ();
        window .location = $ ( this ) .attr ( "href" );
         Return  false ;
    });

});

Now the most important - is the server part of our plug-in, which actually happens preservation, processing and parsing of data.
The following code shows the class methods Menu, admin controller and adapted to the framework codeigniter, the request can lay out a fully functional version of the plug-in for codeigniter:

// Save the menu order nestable 
    function  menu_sortable_save () {
         if ( $ this -> input-> Post ()) {
             $ jsonstring = $ this -> input-> Post ( 'jsonstring' );
             // decode the array 
            $ jsonDecoded = {
                     $ returnSubSubArray = array ();
                     if ( isset ( $ subArray [ 'Children' ])) {
                         $ returnSubSubArray = parseJsonArray ( $ subArray [ 'Children' ], $ subArray [ 'ID' ]); 
              
                    }
                    $ Return [] = array ( 'ID' => $ subArray [ 'ID' ], 'parentID' => $ parentID );
                     $ Return = array_merge ( $ Return , $ returnSubSubArray );
                }
                Return  Return $ ;
            }
            $ ReadbleArray = parseJsonArray ( $ jsonDecoded );
             // loop iterates through the array and stored in the database 
            foreach ( $ readbleArray  as  $ Key => $ value ) {
                 if (is_array ( $ value )) {
                     $ Data = array (
                         'order' = > $ Key ,
                         'parent_id' => $ value [ 'parentID' ]
                    );
                    $this ->db->where( 'id' , $value [ 'id' ]);
                     $this ->db->update( 'menu' , $data ) or  $this ->admin_lib->set_admin_alerts( 'alert_danger' , 'Системное message - Error when sorting records' , 'admin / menu / menu_list_sortable' ) ;;
                }
            }
            // Print the message on the page 
            echo  "The order of the categories in successfully saved" . date ( "ymd H: i: S" ). "!" ;
        }
    }


As promised the source application.


Catching backend development, each programmer is faced with the fact that any tree structure - whether it be a menu or list of categories you want displayed on the site are not the usual drop-down list, and beautifully decorated, that user would be convenient to use your CMS! You can nicely formatted output blocks, indenting child partitions, but streamlined sections will still not comfortable. In support comes powerful jQuery plugin Nestable.

Nestable download it, please visit the developer http://dbushell.github.io/Nestable/
Now let's create the menu tree sorted drag and drop: 
The database will have a standard structure. id, name, parent_id and cell sorting order for the values.

So take a sample of all parent categories and put the results into an array:


$ Sql = " SELECT * FROM menu WHERE parent_id = '0'  ORDER  BY  order ";
$ Result = mysql_query ($ sql, $ connection);
$ NumRows = mysql_num_rows ($ result);



Now we derive the page block with parent elements
echo  "<div class = 'cf-nestable Lists'> \ n" ;
  echo  "<div class = 'dd' ID = 'nestableMenu'> \ n \ n" ;
   echo  "<ol class = 'dd-list'> \ n " ;  
    while ( $ row = mysql_fetch_array ( $ result )) {
     echo  "\ n" ;    
     echo  "<li class = 'dd-Item' Data-ID = '{$ row [' ID ']}'>" ;
     echo  "<div class = 'dd-handle'> {$ row ['ID']}: {$ row ['name']} </ div>" ;
    menu_showNested ( $ row [ 'ID' ]);    
     echo  "</ li> \ n" ;
   }   
  echo  "</ ol> \ n \ n" ;
  echo  "</ div> \ n" ;
 echo  "</ div> \ n \ n" ;
  
// The unit must be here, do not move it 
echo  "<div ID = 'sortDBfeedback' style = 'border: 1px solid #eaeaea; padding: 10px; margin: 15px;'> </ div> \ n" ;

Perhaps you have noticed function menu_showNested? Now we will use a recursive function to display all child categories.


function  menu_showNested ( $ parentID )  {
  $ sql = "SELECT * FROM WHERE parent_id menu = '$ parentID' ORDER BY order" ;
  $ result = mysql_query ( $ sql , $ connection );
  $ numRows = mysql_num_rows ( $ result );
 
 if ( $ numRows > 0 ) {
   echo  "\ n" ;
   echo  "<ol class = 'dd-list'> \ n" ;
    while ( $ row = mysql_fetch_array ( $ result )) {
     echo  "\ n" ;    
     echo  " <li class = 'dd-Item' Data-ID = '{$ row [' ID ']}'> \ n " ;
      echo  "<div class = 'dd-handle'> {$ row ['ID']} : {$ row ['name']} </ div> \ n " ;
     menu_showNested ( $ row [ 'ID' ]);    
     echo  "</ li> \ n" ;
   }
  echo  "</ ol> \ n" ;
 }
}
All menus we derived.

Now the hardest part - the creation and transfer of the array in the format json handler on the server and save the data in the database

// ========================================== Nestable script 
function  lagXHRobjekt ()  {
     var XHRobjekt = null ;
     try {
        ajaxRequest = new XMLHttpRequest (); // Firefox, Opera, ... 
    } catch (Err1) {
         try {
            ajaxRequest = new ActiveXObject ( "Microsoft.XMLHTTP" ); // Noen IE v. 
        } catch (ERR2) {
             try {
                ajaxRequest = new ActiveXObject ( "Msxml2.XMLHTTP" ); // Noen IE v. 
            } catch (ERR3) {
                ajaxRequest = false ;
            }
        }
    }
    Return ajaxRequest;
}

// Function to send by post to the order of the array in json format 
function  menu_updatesort (jsonstring)  {
    mittXHRobjekt = lagXHRobjekt ();
    if (mittXHRobjekt) {
        mittXHRobjekt.onreadystatechange = function ()  {
             if (ajaxRequest.readyState == 4 ) {
                 var = ajaxDisplay document .getElementById ( 'sortDBfeedback' );
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            } else {
                 // comment out this line if you do not want to display the spinner download 
                document .getElementById ( 'sortDBfeedback' ) .innerHTML = "<img style = 'height: 11px;' src = '/ Themes / admin / Images / loading.gif' alt = 'ajax-loader' /> " ;
            }
        }
        var tosend = "jsonstring =" + jsonstring;
        ajaxRequest.open ( "POST" , "/ admin / menu / menu_sortable_save /" , True );
        ajaxRequest.setRequestHeader ( "Content-type" , "Application / x-www-form-urlencoded" );
        ajaxRequest.send (tosend);
    }
}

$ ( document ) .ready ( function ()
 {
     // update function menu items 
    var updateOutput = function (e)
     {
         var list = e.length? e: $ (e.target),
            output = list.data ( 'output' );
         if ( window .json) {
            output.val ( window .JSON.stringify (list.nestable ( 'serialize' ))); //, null, 2)); 
            menu_updatesort ( window .JSON.stringify (list.nestable ( 'serialize' )));
        } else {
            output.val ( 'JSON Browser support required for this Demo.' );
        }
    };

    // Call the function to change the order of menu entries in the database. 
    $ ( '#nestableMenu' ) .nestable ({Group: 1 }). on ( 'Change' , updateOutput);

    // Output the initial sequence if the item exists on the page 
    var variable = $ ( '#nestableMenu' ) .data ();
     if ( typeof variable! == "undefined" && variable) {
        updateOutput ($ ( '#nestableMenu' ) .data ( 'output' , $ ( '# nestableMenu-output' )));
    }

    // Button to deploy svetnut menu 
    $ ( '# nestable-menu' ) .on ( 'Click' , function (e)
     {
         var target = $ (e.target),
            Action = target.data ( 'Action' );
         if (Action === 'Expand-All' ) {
            $ ( '.dd' ) .nestable ( 'ExpandAll' );
        }
        if (Action === 'Collapse-All' ) {
            $ ( '.dd' ) .nestable ( 'CollapseAll' );
        }
    });

    // Fix allows you to click on links in nestable 
    $ ( ".dd A" ) .on ( "mousedown" , function (Event)  { // Prevent mousedown nestable Click
        event.preventDefault ();
        Return  false ;
    });
    $ ( ".dd A" ) .on ( "Click" , function (Event)  { // Event Click
        event.preventDefault ();
        window .location = $ ( this ) .attr ( "href" );
         Return  false ;
    });

});

Now the most important - is the server part of our plug-in, which actually happens preservation, processing and parsing of data.
The following code shows the class methods Menu, admin controller and adapted to the framework codeigniter, the request can lay out a fully functional version of the plug-in for codeigniter:

// Save the menu order nestable 
    function  menu_sortable_save () {
         if ( $ this -> input-> Post ()) {
             $ jsonstring = $ this -> input-> Post ( 'jsonstring' );
             // decode the array 
            $ jsonDecoded = {
                     $ returnSubSubArray = array ();
                     if ( isset ( $ subArray [ 'Children' ])) {
                         $ returnSubSubArray = parseJsonArray ( $ subArray [ 'Children' ], $ subArray [ 'ID' ]); 
              
                    }
                    $ Return [] = array ( 'ID' => $ subArray [ 'ID' ], 'parentID' => $ parentID );
                     $ Return = array_merge ( $ Return , $ returnSubSubArray );
                }
                Return  Return $ ;
            }
            $ ReadbleArray = parseJsonArray ( $ jsonDecoded );
             // loop iterates through the array and stored in the database 
            foreach ( $ readbleArray  as  $ Key => $ value ) {
                 if (is_array ( $ value )) {
                     $ Data = array (
                         'order' = > $ Key ,
                         'parent_id' => $ value [ 'parentID' ]
                    );
                    $this ->db->where( 'id' , $value [ 'id' ]);
                     $this ->db->update( 'menu' , $data ) or  $this ->admin_lib->set_admin_alerts( 'alert_danger' , 'Системное message - Error when sorting records' , 'admin / menu / menu_list_sortable' ) ;;
                }
            }
            // Print the message on the page 
            echo  "The order of the categories in successfully saved" . date ( "ymd H: i: S" ). "!" ;
        }
    }


As promised the source application.

4 comments:

Ubek said...

Can You Reupload for me please

Anonymous said...

i would like that 2

Anonymous said...

hi, the source download link is broken. i would very pleased if you can fix it. thanks a lot

LuckyBoy said...

Thanks for the help!! save my day :-)

Post a Comment

Followers

រឿង ដែលខានមើលមិនបាន

Contact us

Name

Email *

Message *

Your Language

Online

Copyright 2009 Simplex Celebs All rights reserved Designed by www.sruol9.com