utt50
utt50

Reputation: 155

JQuery UI Sortable: Save keys with sort order

I am using this code to save my JQuery UI sort order:

$(function() {
    $('#sortable').sortable({
    update: function (event, ui) {
        var data = $(this).sortable('serialize');
        $.ajax({
            data: data,
            type: 'POST',
            url: '/sort.php'
            });
        }
    });
    $( "#sortable" ).disableSelection();
});

This produces an array of numbers. Let's say I also want to save keys with the numbers, based on tags in my list items.

So for example a sorted list such as:

<ul id='sortable'>
<li id='item-3' name='special'><image src='special.jpg'></li>
<li id='item-1' name='normal'><image src='normal.jpg'></li>
<li id='item-2' name='extraordinary'><image src='extraordinary.jpg'></li>
</ul>

Would produce this array in PHP:

$item['special'] = 3;
$item['normal'] = 1;
$item['extraordinary'] = 2;

I know how to access the tags with JQuery but not how to serialize these into an array to pass to my PHP script along with the sorted numbers. Help!

Upvotes: 1

Views: 3412

Answers (2)

utt50
utt50

Reputation: 155

Thanks, dfsq! I also found toArray, which works if you only need the keys.

$(function() {
    $('#sortable').sortable({
    update: function (event, ui) {
        var data = $(this).sortable('toArray', {attribute: 'data-name'});
        //alert(data);
        $.ajax({
            data: {data:data},
            type: 'POST',
            url: 'post.php'
            });
        }
    });
    $( "#sortable" ).disableSelection();
});

Upvotes: 2

dfsq
dfsq

Reputation: 193311

You can construct data object manually with keys as name attribute and value index of the element (plus 1, it's zero-based):

$('#sortable').sortable({
    update: function (event, ui) {
        var data = {};
        $('#sortable').children().each(function() {
            data[$(this).attr('name')] = $(this).index() + 1;
        });
        $.ajax({
            data: data,
            type: 'POST',
            url: '/sort.php'
        });
    }
});
$("#sortable").disableSelection();

Then on the server you will have POST array like $_POST['normal'] = 1, etc.

Alternatively you could pass items as part of items "nested" array:

data['item[' + $(this).attr('name') + ']'] = $(this).index() + 1;

and have POST array like $_POST['item']['normal'] = 1.

Upvotes: 0

Related Questions