jawad
jawad

Reputation: 261

Uncaught TypeError: Converting circular structure to JSON

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.

Upvotes: 25

Views: 30783

Answers (2)

t.niese
t.niese

Reputation: 40862

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.

Upvotes: 28

DoctorFox
DoctorFox

Reputation: 173

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)

Upvotes: 5

Related Questions