Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery UI sortable: restore position based on some condition

I call sortable.stop() to make an ajax call to store some data after drag & drop operation.

When the ajax call returns an error (application logic error or net problem) I want to move the dragged element to its original/start position, how can I achieve it?

The scenario should be

  1. user drags A to B
  2. the sortable.stop() event is called, it triggers an ajax call
  3. the ajax call returns an error
  4. inside the stop() event we get the ajax error
  5. move A to its original position
  6. user again move A to B
  7. everything is ok
  8. A remains in its new position in B

Steps 6-8 are shown to clarify a successive drag can be done and previous error must be forgotten.

like image 783
dafi Avatar asked Apr 18 '10 07:04

dafi


3 Answers

Have a look at .sortable('cancel'); something like this:

var list = $('#some-list')
list.sortable(
{
    // Some options.
    stop: function()
    {
        $.post('some-url', someData, function()
        {
            if (somethingWentWrong)
            {
                list.sortable('cancel');
            }
        });
    }
});
like image 171
Will Vousden Avatar answered Nov 05 '22 04:11

Will Vousden


Thanks to dafi - this works for me:

$('#some-list').sortable({
  // other options here,
  receive: function(event, ui) {

    // ajax or function here
    if(somethingWentWrong) {
       $(this).sortable('cancel');
       $(ui.sender).sortable('cancel');
    }

  }

 });

I'm not sure if you need $(this).sortable('cancel');, but I figure it's best to cancel the source and the destination sortable lists. This way the list item reverts immediately. Other Sortable options here.

like image 28
liveat60fps Avatar answered Nov 05 '22 05:11

liveat60fps


Thanks, liveat60fps , its the second statement out of the two which you only need.

$('#some-list').sortable({

      // other options here,
  receive: function(event, ui) {

    // ajax or function here
    if(somethingWentWrong) {
       $(this).sortable('cancel');
       $(ui.sender).sortable('cancel');
    }    
  }    
});

This way on a certain condition, you can revrt back to the orignal state.

like image 29
varun kalra Avatar answered Nov 05 '22 04:11

varun kalra