0

I'm sending JSON via a websocket, but some of the created messages are empty.

function chVol(vol){
 var send = {};
 send["payload"] = {};
 send["payload"]["volume"] = vol;
 ws.send(JSON.stringify(send));
}

If vol has the value 0 or 1, the messages are correct and at some other values of vol, too. I'm changing vol with a slider and when I'm logging JSON.stringify(send) all messages are correct, but not when

ws.onmessage = function (e) {
            data = JSON.parse(e.data);
            console.log(data);
};

is called. Any ideas what is going on here?

1
  • It's not clear what you're asking. onmessage is for incoming messages, it won't log outgoing messages you sent using .send(). Is that the confusion? Commented Oct 14, 2015 at 6:31

1 Answer 1

2

You can't do this:

var send = {};
send["payload"]["volume"] = vol;

That will cause an exception, as you're attempting to access the property 'volume' on undefined.

You need to first initialize send['payload'] to an empty object:

var send = {}
send['payload'] = {}
send['payload']['volume'] = vol
Sign up to request clarification or add additional context in comments.

3 Comments

Or you could make the definition in to a single object declaration: var send = { payload: { volume: vol } }; +1 for fixing the problem regardless.
i didn't copy the whole code, because there a much more parameters that I submit. send["payload"] = {}; is in the code before...
@JohannesGi then please update your question and include code that actually works. It's important to include a minimal complete example, otherwise we cannot help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.