I am new at nodes, express, mongodb and socket.io. Things have been working pretty smooth up and till now. So i am building this small test application where the user inputs his name and then post a question.
The socket.io receives the data (username and question) but upon returning the data is says null. (In the beginning it was working but then i started with installing mongoose and things went wrong from that point on). I work with the express framework and all the necessary modules are installed.
in my views this is the code for connection to socket and updating the data:
<script>
$(document).ready(function()
{
var socket = io();
$("#btnAskQuestion").on("click", function(e)
{
//get the value of the inputfield and textarea
var username = $('#inputQuestion').val();
var question = $('#question').val();
var result = "<p>Username: </p>" + username + " <br /><br /> " +
"<p>Question: </p>" + question + " <br /> <br /> ";
console.log("Values of inputfield & textarea: " + result);
//makes the connection to the server and send the data
var socket = io.connect('http://localhost:3000');
socket.emit('sendQuestion', result);
console.log("Gets send: " +result);
//alert('test');
});
//returns the updated data + visualize it on the page
socket.on('updateQuestion', function (data)
{
console.log("Updated data: " + data);//data is the username and question = result
$('#answer').css("border", "4px solid #9C27B0");
$('#answer').css("borderRadius", "8px");
$('#answer').css("padding", "10px");
$('#answer').css("fontSize", "16px");
$('#answer').append('<li>'+data+'</li>');
});
});
</script>
in my bin>www file i have the following code for the server-side connection:
var io = require('socket.io')(server);
io.on('connection', function (socket)
{
socket.on('sendQuestion', function (data)
{
console.log("The server received a question");
console.log(data);
// send question to ALL clients
io.sockets.emit("updateQuestion", data.result);
});
});
In chrome browser i run the developer tools and the output is the following screenshot: http://www.nappdev.be/clientside.png
This is a screenshot from the server-side where it logs the data http://www.nappdev.be/serverside.png
I hope somebody can help me out because i don't see why its returning null
Thanks in advance !!1
[edited: just noticed that you are actually sending data.result which is null in the first place]
Instead of sending data.result send data.
Note that this will give you the whole string (username + question). If you only want the question, you will have to parse the received string on the server side and emit only the question to the connected clients.