0

jQuery Code: I removed all my Sortable settings. If you feel they are pertinent I can put them back in.

$('#navsort').sortable({ ... });

$("#content").on('click', '#submit_menu', function (event){
    event.preventDefault();
    $.ajax({
        type: "POST",
        url: "menu-ajax.php",
        data: { data:$('#form').serialize() }
    }).done(function (response) {
        $('#content').hide().html(response).fadeIn('slow');
    });
});

HTML Code: This is a simplified version because the real code has lots of PHP and other stuff going on.

<div id="content">
    <form method="post" id="form">
        <a href="#" id="submit_menu">Save</a>
        <ol id="navsort">
            ...
        </ol>
    </form>
</div>

As you can see the entire form, including the elements attached to Sortable, are replaced (with an identical copy of itself) via AJAX when the form is submitted. This is when Sortable stops working.

I understand that the new form was not part of the DOM when Sortable was initialized and so its not attached despite being identical to the form it replaced. I also understand how .on() is used to delegate between elements that are present when the page first loads and those added afterwards. What I do no understand is how to apply this concept to the initialization of Sortable.

I got it to work with a dirty hack, but I want to understand the right way.

Dirty Hack:

function dirtyhack(){
    $("selector").on('event', 'target', function (){ ... });
}
dirtyhack();

$("#content").on('click', '#submit_menu', function (event){
    event.preventDefault();
    $.ajax({
        type: "POST",
        url: "menu-ajax.php",
        data: { data:$('#form').serialize() }
    }).done(function (response) {
        $('#content').hide().html(response).fadeIn('slow');
        dirtyhack();
    });
});

So Sortable is initialized when the page loads and reinitialized when AJAX is done replacing the elements Sortable is attached to. Maybe this is right, but it feels wrong.

Disclosure: I am actually using the nestedSortable plugin in place of Sortable, but the plugin author claims that "All jQuery Sortable options, events and methods are available" through his plugin. I also did switch to the standard Sortable Widget to test and had the same issue, so I do not think its the plugin.

Plugin URL: https://github.com/mjsarfatti/nestedSortable/tree/2.0alpha

Kirkland
  • 2,319
  • 4
  • 20
  • 27

0 Answers0