25
votes

I have a tableDnD drag and drop with JSON.stringify :

jQuery(document).ready(function() {
    jQuery("#Table").tableDnD({
        onDragClass: "danger",
        onDrop: function(table, row) {
            jQuery.ajax({
                url: "ajax.php",
                type: "post",
                data: {
                    'rows' : JSON.stringify(table.tBodies[0].rows)
                },
                dataType: 'html',
                success: function(reponse) {
                    if(reponse) {
                        //alert('Success');
                    } else {
                        alert('Erreur');
                    }
                }
            });             
        }
    });
});

I have this error message:

Uncaught TypeError: Converting circular structure to JSON

I have the problem only on Chrome.

2
You're trying to convert a nodeList / DOM elements to a JSON string - adeneo
yes, it works on Firefox, but it gives problem in Chrome - jawad
If it works, it's a fluke, you can't convert nodelists to strings, or at least you shouldn't. - adeneo
Thank you for your answers, can you offer me another solution? - jawad
Why do you have to send the entire element to the server? Usually you'd extract a value or text from the element, not send the whole thing (which isn't really possible) - adeneo

2 Answers

27
votes

You should not convert a DOM element to JSON directly.

While - like you already experienced - it fails e.g. in Chrome, the results may also be unexpected.

The reason for this is because the data is circular:

A Node has the property childNode containing all its children and the property parentNode pointing to the parent.

The JSON format does not support references, so it will need to follow the properties until an end is reached, but because a child points to its parent which has a list of its children, this is an endless loop, that’s the reason why you get the error:

Uncaught TypeError: Converting circular structure to JSON

Even if this is resolved by the browser you may have other problems. Because not only childNodes exist but also childElements. The same is for parentNode/parentElement, then you also have nextSibling, prevSibling, firstChild, lastChild, ... that would probably also be followed, so you would end up in the terrifying large JSON file containing a butch of duplicate data.

5
votes

You need to use the .innerHtml property of the DOM element instead of converting the entire DOM element. So you should be looking to have something like:

JSON.stringify(table.tBodies[0].innerHTML)