0

I created this code to send user invites by websocket but It doesn't work and shows this error:

Uncaught TypeError: Converting circular structure to JSON

$.each(formAttibutes, function(index, formAttribute){
    if (formAttribute[0].value !== 0) {
        if (formAttribute[1].value !== 0) {
            var friend = {
                "name": formAttribute[0],
                "description": formAttribute[1],
            };
            socket.send(JSON.stringify(friend));
        }
    }
});

Oh gosh I'm sleepy, sorry. As you said infinity reference (replace formAttribute[1] >> formAttribute[1].value) thanks!

davidwillianx
  • 391
  • 2
  • 5
  • 13
  • So is it circular? You need to show us what `formAttribute` refers to. – nnnnnn Jan 14 '15 at 11:21
  • 1
    What are the values in the `formAttributes` array that you are trying to encode? – Rory McCrossan Jan 14 '15 at 11:22
  • check this [link](http://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json) – Luca Jan 14 '15 at 11:22
  • possible duplicate of [Converting circular structure to JSON -- Any way to find what field it is complaining about?](http://stackoverflow.com/questions/7005205/converting-circular-structure-to-json-any-way-to-find-what-field-it-is-compla) – grattmandu03 Jan 14 '15 at 11:23
  • This means - `formAttribute[x]` or one/more of its properties reference itself or one of its parents. Trying to stringify it will be a never ending process. Hence the error. – techfoobar Jan 14 '15 at 11:23
  • @RoryMcCrossan formAttributs its 2 elements 1 - input / 2 - textarea – davidwillianx Jan 14 '15 at 11:24
  • HTML elements cannot be encoded to JSON. You need to select their values. – Rory McCrossan Jan 14 '15 at 11:25
  • @techfoobar could you sugst something? – davidwillianx Jan 14 '15 at 11:26
  • @smartphonne - DOM elements contains (among other things) a link to their immediate parent in the property `parentNode` - which makes them circular in structure. I suggest you create a custom object containing just the data you need and stringify that instead. – techfoobar Jan 14 '15 at 11:29
  • @smartphonne - Check the answer I posted, I believe thats what you want. – techfoobar Jan 14 '15 at 11:33

1 Answers1

0

I think you are looking to have a JSON stringified object containing the values in those elements (and not the elements themselves). For that, you can do:

...

var friend = {
    "name": formAttribute[0].value,
    "description": formAttribute[1].value
};
socket.send(JSON.stringify(friend));

...

Note: The above is assuming formAttribute[0] and formAttribute[1] are DOMElements. If they are jQuery objects, you should use .val() instead.

techfoobar
  • 65,616
  • 14
  • 114
  • 135