1

I am using mongodb with mongoose to maintain a list of stocks across clients. I want to simultaneously update the list using socket.io when one user makes a change. I can connect to the socket and update client javascript but not make changes to variable on server side.

app.js - Server

// connect to socket.io
io.on('connection', function (socket) {
   console.log('Client Connected..');

    ///retrieve new stock from client
    socket.on('submitStock', function (data) {
       console.log(data);
       ///do mongodb stuff here

       ///send new stocks to all clients
       socket.emit('activeStocks', data);
     });
});

script.js - client

var socket = io.connect();

///connect to socket
socket.on('connect', function (data) {
   socket.emit('join', 'Hello World from client');
});

///use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
    //var stockList = $('#stockList');
    socket.emit('submitStock', 'here is the data');
});

//retrieve the new stock from the server and update list
socket.on('activeStocks', function(data) {
   //how to update activeStocks here??
   console.log(data);
});

index.ejs

<% if (message.length > 0) { %>
   <div class="alert alert-danger"><p><%= message %></p></div>
<% } %>

<div class="container">
  <form id="addStock" action="/add" method="post">
    <div class="form-inline">
      <input type="text" class="form-control" name="stockTicker" placeholder="Enter a stock ticker">
      <button type="submit" class="btn btn-primary"><span>Add Stock</span></button>
    </div>
  </form>
</div>

<% if (activeStocks) { %>
  <% for (var i=0; i< activeStocks.length; i++) { %>
    <div> <%- activeStocks[i] %></div>
  <% } %>
<% } %>
andrewgi
  • 620
  • 1
  • 7
  • 22
  • Does your client emit `socket.emit('submitStock', 'here is the data');` ? Can we start from checking it? – mk12ok Jul 03 '17 at 17:30
  • yes the socket works fine, i get a log with 'here is the data'. But if I try to write a new activeStock the ejs file won't read it – andrewgi Jul 03 '17 at 17:32
  • You can add `var activeStock;` to the client code and add `activestock = data;` line to the `socket.on('activeStocks', ..` section in the client. – mk12ok Jul 03 '17 at 17:41
  • thats what I was trying, it should display the activeStocks on 'index.ejs' as 'here is the data' correct? it only displays the stocks from mongoDB previously displayed – andrewgi Jul 03 '17 at 17:52
  • It will not display stock, you have to refresh the view after receiving `data` from the server. Please show the entire code of `index.ejs` – mk12ok Jul 03 '17 at 19:42
  • the necessary variable should refreshed automatically after `socket.on('activeStocks'..` no? i can't reload the enter window or else the route will add another stock. the additional index.ejs is posted – andrewgi Jul 03 '17 at 20:28
  • No, it will not refresh automatically. Give me a minute, I will try to show you some example – mk12ok Jul 03 '17 at 22:36

2 Answers2

1
  1. Suppose that we have a div in index.js let it be <div id="stocks">,
  2. Let data be an array of strings,

Try the following code:

socket.on('activeStocks', function(data) {
    document.getElementById('stocks').innerHTML = '';
    data.forEach( function (stock) {
        document.getElementById('stocks').innerHTML += stock + '<br>';
    });
});
mk12ok
  • 1,293
  • 14
  • 14
  • that would work normally but im using Mongo to get the stocks and an ejs variable to display them so I couldn't rewrite the entire stock list. upvoted for the suggestion though – andrewgi Jul 04 '17 at 23:30
  • Maybe not rewrite but append the new item? – mk12ok Jul 04 '17 at 23:33
0

Since I was using mongoDB and the variable activeStocks in index.ejs I couldn't rewrite or append the html. I needed the mongo Id's for potential removal in the future. I went with a partial refresh of the div taken from this question: Refresh/reload the content in Div using jquery/ajax

index.js

var io = require('../server');

io.on('connection', function (socket) {
  console.log('Client Connected..');

  ///retrieve new stock from client
  socket.on('submitStockToServer', function (data) {
    ///send new stocks to all clients except socket that started it.
    socket.broadcast.emit('newStockToClient', data);
  });

  socket.on('updateMyStocks', function (data) {
    ///only send to each updated client
    socket.emit('updated', data);
  });
});

script.js

var socket = io.connect();

//connect to socket
socket.on('connect', function () {
  console.log('connected');
});

//use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
  //var stockList = $('#stockList');
  socket.emit('submitStockToServer');
  console.log('submitted');
});

//retrieve information on new stock and send back request to server
socket.on('newStockToClient', function() {
  socket.emit('updateMyStocks', 'Your stocks are now updated');
});

//check if its updated
socket.on('updated', function () {
  ///partially reload stock div
  $("#stockContainer").load(location.href+" #stockContainer>*","");
});

index.ejs

<div id="stockContainer">
  <% if (activeStocks) { %>
    <% for (var i=0; i< activeStocks.length; i++) { %>
      <div> <%- activeStocks[i] %></div>
    <% } %>
  <% } %>
</div>
andrewgi
  • 620
  • 1
  • 7
  • 22