Jquery sortable list, return only affected (swapped) items

Hello all,

I am using the Jquery sortable demo from:


What if I have a list of 40 items, in the example the ordering with a query that will be looped 40 times. This seems a little silly to me, only two items are affected.

Is there a way to return only the two affected elements?

Who is Participating?
AdamSenior DeveloperCommented:

I understand what you mean, but you have to be a bit careful here.
Just because only 2 items have been moved, it does not mean that only 2 items need to be updated in the database.
For example, if you move the bottom item to the top, all items will have changed place by one and will need updating.

However, that being said, if an item has been moved by just one place, then only two items need updating in the database, and changing them all is inefficient.

One way to deal with this would be to save the .sortable('serialize') results before the first sort, and each time the update event is called. You can then compare the previous order with the new order, and only send the changed positions to the PHP script to update the database.

Here's a start to the code, though I don't have time to complete it, it should be enough to get you started.

$(document).ready(function() { 

// Save the initial sort order
var oldOrder = $('#test-list').sortable('serialize');

    handle : '.handle', 
    update : function () { 
      var order = $('#test-list').sortable('serialize'); 

      var changedItems = compareOrder(order, oldOrder);

      $("#info").load("process-sortable.php?"+changedItems ); 

      // Save the updated sort order for the next time the list is sorted.
      oldOrder = $('#test-list').sortable('serialize');

function compareOrder(newOrder, oldOrder) {

    // Comparison code goes here


Open in new window

The changedItems list will need to include both item, and its position, and the PHP code will need to take this into account when building the SQL
wal_toorAuthor Commented:
Thanks cyber spy,

I have'nt thought of what you said. makes sense. Thanks for your reply. I'll dive into this.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.