Drag drop not working on dynamic elements / Drag drop not working after ajax request / jQuery sortable not working

If you are using drag drop of rows from one table to another or on the list items, chances are that you are using jQuery’s Sortable widget. Suppose you have two tables with id as table1 and table2 and you are using following code to drag-drop their rows :

$(“#table1 tbody, #table2 tbody”).sortable({
         connectWith : “#table1 tbody, #table1 tbody”
});

This works fine when table rows (or the list) are present at page load time. But it might be the case that table rows are populated with dynamic data from the server on the basis of some event such as on opening of a modal box which means that table rows are created using ajax as below :

$.ajax({
      url : ‘serverUrl’,
      data : ‘id=’+id,
      success : function(response) {
                          // method which populates table rows
                          populateTableRows(response);
                     }
});

This works perfect most of the times but sometimes it happens that when the table rows are populated after the ajax call, the rows could not be dragged and dropped. If you are facing the same problem then the solution lies below.

Solution

The simplest solution is to call sortable()on the items which you desire to be draggable after the ajax function completes. The best place would be to call it from the successfunction of your ajax request. Let’s say the code which attaches drag-drop functionality over your elements (be it a table or a list) is written inside a function as :

function attachDragDrop() {
     $(“#table1 tbody, #table2 tbody”).sortable({
            connectWith : “#table1 tbody, #table1 tbody”
      });
}

The ajax call which creates the element should be rewritten as :

$.ajax({
      url : ‘serverUrl’,
      data : ‘id=’+id,
      success : function(response) {
                          // method which populates table rows
                          populateTableRows(response);
                         // attach drag-drop functionality here
                         attachDragDrop();
                     }
});

After the elements are added to the page or DOM (Document Object Model) from the response of ajax request, the function which calls sortableagain attaches drag-drop support to them.

If this post helped you, do take out some time to comment / share it. If it didn’t solve your problem, comment in the space below so that we can support.

Leave a Reply