user94628
user94628

Reputation: 3721

Extracting real-time server-side data for client-side application

I'm using websockets to send data from the server to the client. This works fine so for example I can display messages the server is sending to the client as they are received. This is the partial javascript I use:

    ws.onmessage = function(evt){
            $("#display").append(evt.data + "<br />");

            console.log(evt.data);

This is the data displayed:

{"place": {"full_name": "Northampton, Northamptonshire"}, "coordinates": {"type": "Point", "coordinates": [-0.9003352, 52.2467064]}}

But if I just wan the coordinate information i,e, the longitude and latitudes then the web console error message is:

TypeError: evt.data.coordinates is undefined @ http://localhost:8888/:34

I'm trying to get this data by doing:

    ws.onmessage = function(evt){
            var coordinates = evt.data.coordinates.coordinates;
            console.log(coordinates);

I'm a newbie to javascript.

Thanks

Upvotes: 2

Views: 318

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

evt.data is a JSON string. You have to parse it :

ws.onmessage = function(evt){
   var msg = JSON.parse(evt.data);
   var coordinates = msg.coordinates.coordinates;

Upvotes: 2

Related Questions