1

I'm going through a Node, Express, & Socket.io chat tutorial. I decided to use Redis to store the chat history and have successfully set it up so that my information is correctly posting to the database. I am now trying to access that information to use on the client-side (in this case I'm trying to access the list of users currently in the chat so I can show them to the side of the chat). I am using $.getJSON to make a GET request. Right now I have it setup so that the file it tries to access only has this JSON object : {"dog" : "2","cat":"3"} just to test it, and that is working, but I'm not sure where to go from there because anytime I try adding a function into that file, even if I specify to return a JSON object and call that function, the request stops returning the correct information.

For example I tried :

var data = function(){
    return {"dog" : "2","cat":"3"}
}
data();

and that doesn't return anything ( I understand that when I make a GET request the function isn't run, but it doesn't even return that text, and if it doesn't run a function than I'm not sure how I can access redis from this file)

Here's what I'm thinking:

var redis = require('redis')

//figure out how to access the redis client that I have at localhost:6379, something like var db = redis.X

//and then call (for example) db.smembers('onlineUsers') and be returned the object which I can iterate through

Here's my relevant code:

server.js:

var jade = require('jade');
var PORT = 8080;

var redis = require('redis');
var db = redis.createClient();
var pub = redis.createClient();
var sub = redis.createClient();

var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(PORT, function(){
  console.log("Now connected on localhost:" + PORT)
});

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
 res.render('home');
});

io.sockets.on('connection', function(client){

  sub.subscribe("chatting");
  sub.on("message", function (channel, message) {
        console.log("message received on server from publish");
        client.send(message);
    });

  client.on("sendMessage", function(msg) {
            pub.publish("chatting",msg);
        });

  client.on("setUsername", function(user){
            pub.publish("chatting","A new user in connected:" + user);
            db.sadd("onlineUsers",user);
        }
    );

  client.on('disconnect', function () {
        sub.quit();
        pub.publish("chatting","User is disconnected :" + client.id);
    });
});

script.js:

$(document).ready( function(){
    $client = io.connect();
    initialize();
});


var setUsername = function(){
    var username = $("#usernameInput").val();
    if (username)
    {
        var user = username;
        $client.emit('setUsername', username);
        $('#chatControls').show();
        $('#usernameInput').hide();
        $('#usernameSet').hide();
        showCurrentUsers();
    }
}

var showCurrentUsers = function(){
    $('#list_of_users').empty();

    $.getJSON('getusers.js', function(data){
        for (var i = 0; i < data.length; i++){
            $('list_of_users').append("<li>"+data[i]+"</li>")
        }
    })

}

var sendMessage = function(){
    var msg = $('#messageInput').val();
    var username = $("#usernameInput").val();
    if (msg)
    {
        var data = {msg: msg, user: username}
        $client.emit('message', data);
        addMessage(data);
        $('#messageInput').val('');
        // populate(username,msg);
    }
}


var addMessage = function(data) {
    $("#chatEntries").append('<div class="message"><p>' + data.user + ' : ' + data.msg + '</p></div>');
}


// var populate = function(username,msg) {
//     var data ;
// }

var initialize = function(){
    $("#chatControls").hide();
    $("#usernameSet").on('click', setUsername);
    $("#submit").on('click',sendMessage);
    showCurrentUsers();
}

and right now all that the getusers.js file has in it is:

{"dog" : "2","cat":"3"}

1
  • I updated my answer below with some different JQuery to try. I hope it helps! Commented Jun 27, 2014 at 17:03

3 Answers 3

3

It looks like you're expecting your call to $.getJSON to load and execute the javascript it loads. It doesn't work this way. You need to make a node endpoint (via a route) which renders the JSON. The node endpoint would then do the data manipulation / querying redis:

Node:

In routes.js:

app.get('/chatdata', ChatController.getChatData);

In ChatController.js (manipulate, create the data as you like here)

exports.getChatData = function (req, res) {
   var data = function(){
      return {"dog" : "2","cat":"3"}
   };
   res.JSON(data);
};

Front-end

$.getJSON('getChatData', function(data){
    //...
})
Sign up to request clarification or add additional context in comments.

Comments

0

I think you need to setup a route to handle the GET request that $.getJSON makes, or if getusers.js is in the /public directory, then you need to modify your $.getJSON call as follows:

$.getJSON('http://localhost:8080/public/getusers.js', function(data){

3 Comments

I changed it to that, it still isn't returning the JSON from the page, I'm not sure if I'm requesting it incorrectly?
Where is getusers.js located in the directory structure?
In the public folder, I'm referencing the file correctly because when I reference it incorrectly it tells me that it can't find the page I specified, but it isn't actually returning the data.
0

Ok, it looks like it is a problem with your getusers.js file. $.getJSON seems to prefer double quotes. Try formatting it like this:

{ "dog" : "2", "cat" : "3" }

Also, try using this to display the data:

    $.getJSON('getusers.js', function(data){
        var items = [];
        $.each( data, function( key, val ) {
            items.push("<li id='" + key + "'>" + val +"</li>");
        });
        $('#list_of_users').append(items.join(""));
    });

Comments

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.