0

Why do I get "Uncaught TypeError: Illegal invocation" when I post this functions returned object into an ajax post:

base.serialize = function()
{
var data
  , depth = 0;

    step = function(level, depth)
    {       
        var array  = [ ]
          , items = level.children("li");

            items.each(function()
            {
                var   li   = $(this)
                    , item = $.extend({}, li.data())
                    , sub  = li.children("ol");

                    if (sub.length)
                    {
                        item.children = step(sub, depth + 1);
                    }

                array.push(item);
            });

        return array;
    }

data = step(base.$el, depth);

return data;
};

What I'm trying to do is to convert an HTML tree with data values to an array, to save sort order to database:

/*
 * ------------------------------------------------------
 *  Liveflex Treeview
 * ------------------------------------------------------
 */
var tree = $(".dd-list").liveflex_treeview({
      handle        : 'div.dd-handle'
    , opencollapse  : '.opencollapse'
    , itemMoved     : function(e)
                    {
                        var sort_array = e.serialize();

                            // Save order
                            $.post('/url_fetch/sort_posts', { 'sort_array' : sort_array }, function(data)
                            {
                                console.log('Data:' + data);
                            });
                    }
});
Peter Westerlund
  • 741
  • 1
  • 10
  • 36

1 Answers1

2

You're trying to post an object containing DOM elements. But DOM elements have cyclic properties (they all points to the window, for example) and sometimes contains properties you can't fetch. They can't be serialized as JSON (or by any naive function just recursively serializing the properties).

Your solutions might be :

  • to replace the DOM elements with some kind of representation related to your application
  • to use a special function to serialize the DOM elements (see this related question)
Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I don't quite understand. Another similar [plugin](https://github.com/dbushell/Nestable/blob/master/jquery.nestable.js#L137-L160) I tested had `serialize: function() {` in the beginning and works fine. And is part of an `Plugin.prototype = { ... }`. But I can't do so for this plugin because the entire file is structured differently. Just need to get the base.$el tree into an array to send with $post. Can you help me show how it should look like? – Peter Westerlund Jul 17 '13 at 13:19