Svetlana
Svetlana

Reputation: 33

How to use serialized and send ajax (johnny sortable plugin)

I use http://johnny.github.io/jquery-sortable/

I can not understand how to send the serialized data?

My HTML

<ul>
    <li data-id="1">Item 1</li>
    <li data-id="2">
        Item 2
        <ul>
            <li data-id="4">Item 4</li>
            <li data-id="5">Item 5</li>
        </ul>
    </li>
    <li data-id="3">Item 3</li>
</ul>

JS

$(function  () {
    $("ul#menuList").sortable({
        handle: 'i.icon-move',
        itemSelector: 'li',
        placeholder: '<li class="placeholder"/>',
        onDrop: function (item, container, _super)
        {
            //var dataToSend = $("ul#menuList").sortable("serialize").get();

            $.ajax({
                url: "ajax_action.php",
                type: "post",
                data: dataToSend,
                cache: false,
                dataType: "json",
                success: function()
                {}
            });
            //_super(item, container);
        }
    });
});

I tried as described in this question, but it does not work with the ul->li

I need to get an array

[0] => Array
(
    [id] => 1
)
[1] => Array
(
    [id] => 2
    [children] => Array
    (
        [0] => Array
        (
            [id] => 4
        )
        [1] => Array
        (
            [id] => 5
        )
    )
)
[2] => Array
(
    [id] => 3
)

I would be grateful for your help.

Upvotes: 3

Views: 3344

Answers (2)

Michael Konečn&#253;
Michael Konečn&#253;

Reputation: 1764

I was trying to resolve the exact same problem today. This is the solution I came up with. It should give an Array in the exact form you described above.

$(function  () {
  $("ul#menuList").sortable({
    serialize: function ($parent, $children, parentIsContainer) {
      var result = $.extend({}, {id:$parent.attr('id')});
      if(parentIsContainer)
        return $children
      else if ($children[0]) 
        result.children = $children
      return result

    }, 
    onDrop: function ($item, container, _super) {
        // default
        $item.removeClass("dragged").removeAttr("style")
        $("body").removeClass("dragging")
        // END - default

        var dataToSend = $("ul#menuList").sortable("serialize").get();

        //console.log(dataToSend);

        $.ajax({
            url: "ajax_action.php",
            type: "POST",
            data: {"sortedList":dataToSend},
            cache: false,
            dataType: "json",
            success: function () {}
        });
        //_super(item, container);
    }
  })
})      

Upvotes: 3

p.kelly
p.kelly

Reputation: 435

You need to change the serialize function. Look here http://jsfiddle.net/985Mg/

The plugin allows multiple nested lists in one list item. Thus you get one additional level in the default data serialization.

Upvotes: 1

Related Questions