1

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!

2 Answers 2

2

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();
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.