In jQuery, how to revert a draggable on ajax call failure?

NikhilWanpal picture NikhilWanpal · Mar 15, 2011 · Viewed 8k times · Source

I want the draggable to be reverted to its original position if the ajax call on drop returns a failure. Here is the code what I am imagining it to be.. It is OK if the draggable rests in the droppable while the ajax call is in process...

<script type="text/javascript">
jQuery(document).ready($){
    $("#dragMe").draggable();
    $("#dropHere").droppable({
        drop: function(){
            // make ajax call here. check if it returns success.
            // make draggable to return to its old position on failure.
        }
    });
}
</script>
<div id="dragMe">DragMe</div>
<div id="dropHere">DropHere</div>

Answer

NikhilWanpal picture NikhilWanpal · Mar 16, 2011

Thanks for your replay @Fran Verona.

I solved it this way:

<script type="text/javascript">
jQuery(document).ready($){
    $("#dragMe").draggable({
        start: function(){
        $(this).data("origPosition",$(this).position());
        }
    });
    $("#dropHere").droppable({
        drop: function(){
            //make ajax call or whatever validation here. check if it returns success.
            //returns result = true/false for success/failure;

            if(!result){ //failed
                ui.draggable.animate(ui.draggable.data().origPosition,"slow");
                return;
            }
            //handling for success..
        }
    });
}
</script>
<div id="dragMe">DragMe</div>
<div id="dropHere">DropHere</div>

Wanted to avoid any new global variables, also the number of variables was unpredictable as many drag-drops can happen while the first is in progress, i.e. before the 1st call returns..! BTW, for anyone looking for the same answer, .data() does not work on all elements, I am not sure about jQuery.data(), though.. Let me know if anyone finds anything wrong in this! :)