0

SOLVED: Answer is: socket.on('clients', function(data) { document.write(JSON.stringify(data)); });

I want to get ouput like this (only the part in bold) on the screen as JSON:

debug - websocket writing 5:::{"name":"clients","args":[[{"id":6,"name":"demo 3"},{"id":7,"name":"demo1"}]]}

I must be missing something cause I just can't understand why it doesn't print as JSON. I have 3 files:

app.js (server) :

var fs = require('fs');
var db = require("./db.js");

var http = require('http').createServer(function handler(req, res) {
    fs.readFile(__dirname + '/index.html', function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        } else {
            res.writeHead(200);
            res.end(data);
        }
    });
}).listen(3000);
// -----------------------------------
var io = require('socket.io').listen(http);
io.sockets.on('connection', function (client) {
    console.log('Client connected');
    db.get_employees(function (employees) {
        io.sockets.emit('clients', employees);
    });
});

db.js (connect to database) :

// -----------------------------------
var mysql = require('mysql');
var client = mysql.createConnection({
    user: 'xxxx',
    password: 'yyyy',
    host: '123.45.67.89',
    database: 'zzzz'
});
// -----------------------------------
exports.get_employees = function (callback) {
    client.query("select id, name from clients", function (err, results, fields) {
        callback(results);
    });
}

And index.html :

<script src="http://192.168.2.25:3000/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script>
 $(document).ready(function() {
  var socket  = io.connect('http://192.168.2.25:3000');
  socket.on('clients', function(data) {
   $.each(data, function(i, obj) {
        //  document.write(obj);      // Gets me [object Object][object Object]
        //  document.write(obj.name)  // Gets me name column
        //  document.write(obj.email) // Gets me email column
        //  document.write(obj.xxxxx) // Gets me xxxxx column
        //  document.write(JSON.stringify(obj));   //Prints as JSON but structure is   wrong and it is a html string not as JSON output

     });
  });
});
</script>

I am having trouble figuring why I cannot print it as JSON. See index.html commented lines. As well I want it to be a clean JSON output of my database and not as html.

The io.sockets.emit('clients', employees); in the App.js emits a correct json format I want but I can't get it outputted.I get [Object Object] or Undefined. There must be a way to do it because if I have to structure it manually it would make it speed inefficient.

Any help would be appreciated.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
Marty Balandis
  • 19
  • 2
  • 10
  • JSON.stringify is the correct function to use. What do you mean it prints it as html? Can you provide an example of what it outputs? – Rei Mavronicolas Jun 25 '13 at 10:22
  • It outputs: {"id":6,"name":"demo3"}{"id":7,"name":"demo1"} but should output at like this: {"id":6,"name":"demo3"},{"id":7,"name":"demo1"} (with a comma) but idealy I want it like this like the debug emit prints in the console: {"name":"clients","args":[[{"id":6,"name":"demo 3"},{"id":7,"name":"demo1"}]]} however the page is like html text printed. I need it as JSON (how do I change the header of the page too) – Marty Balandis Jun 25 '13 at 10:29
  • I can add , manually but then it will add to the end as well so I need to add another function that removes it and then converts it to JSON header. Seems too many workarounds needed, there must be a simpler and less resource consuming way. – Marty Balandis Jun 25 '13 at 10:31
  • It's because you're outputting each JSON object on it's own. Try doing stringify on the data variable e.g. socket.on('clients', function(data) { document.write(JSON.stringify(data)); }); – Rei Mavronicolas Jun 25 '13 at 10:41
  • The funny thing is that I tried something similar before but didn't work. This actually works! Thank you!. I'll mark this as solved! – Marty Balandis Jun 25 '13 at 10:48
  • I'll convert the comment into an answer for the sake of completeness. – Rei Mavronicolas Jun 25 '13 at 11:49
  • @MartyBalandis it is better to accept a answer instead of prefixing question with solved so please do that – Gaurav Jun 26 '13 at 07:04
  • @Gaurav What answer? The whole answer was in comments which helped, so how could I even accept it? -.- – Marty Balandis Jun 28 '13 at 13:29
  • Reinard Mavronicolas posted the answer later so you can accept it now...or still not able to see the answer?? – Gaurav Jun 30 '13 at 05:18
  • @Gaurav Yes, sorry, I missed that :) – Marty Balandis Jul 18 '13 at 16:12

1 Answers1

1

It's because you're outputting each JSON object on it's own. Try doing stringify on the "data" variable e.g.

$(document).ready(function() {
  var socket  = io.connect('http://192.168.2.25:3000');
  socket.on('clients', function(data) {
    document.write(JSON.stringify(data));
  });
});
Rei Mavronicolas
  • 1,387
  • 9
  • 12
  • This is giving a circular reference error: TypeError: Converting circular structure to JSON – Sumit Bisht Apr 25 '14 at 05:55
  • @SumitBisht - the error you're getting is not due to a problem with the above code. It means you have a circular reference in the object (in this case 'data') you're trying to stringify. Do a search for the error and you'll probably get a better explanation. – Rei Mavronicolas Apr 25 '14 at 07:43
  • Oh,sorry got it.. I was trying to get information about the socket object itself. Getting data is fine, thanks – Sumit Bisht Apr 25 '14 at 10:02