Search code examples
javascriptphpservergetuikitsortables

GetUIkit3 Sortable: Callback


I would like to use UIkit3's sortable to display thumbnails of images and then allow the user to re-order them by dragging/dropping them around. Once completed, I would like the user to press a button, which then calls a PHP function on the server with the the filenames of the images in the sorted order. How does that call look like on the client side?


Solution

  • You just have to use UIkit util to react when sortable stops, that means you finished sorting.

    var util = UIkit.util;
    
    util.ready(function () {
        util.on(document.body, 'stop', function (e, sortable, el) {
            console.log(e.type, sortable, el); //this if for the reference
            //get the elements order in your grid
            var sortResult = { elementsOrder: [] };
            $('#myGridWithElements > div').each(function () {
                var currentEl = $(this)
                var currentElSrc = $('img', currentEl).attr('src'); //src of image inside the div context
                sortResult.elementsOrder.push(currentElSrc);  
            });
    
            $.post( "/admin/save_order",{data: sortResult}).done(function( data ) {
                alert('Yes, you\'ve saved the data');
            }).fail(function(data) { alert('Something gone wrong');});
        });
    });
    

    I've got inspired with the sortable test page https://getuikit.com/assets/uikit/tests/sortable.html