[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 622
  • Last Modified:

Jquery sortable list, return only affected (swapped) items

Hello all,

I am using the Jquery sortable demo from:

http://wil-linssen.com/entry/extending-the-jquery-sortable-with-ajax-mysql/

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?

greetz,
walter
0
wal_toor
Asked:
wal_toor
1 Solution
 
AdamSenior DeveloperCommented:
Walter,

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');

  $("#test-list").sortable({ 
    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
0
 
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.

greetz,
walter
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now