LocalStorage - Seperate Selections - menu

"Any optimization suggestions for js localstorage ?"
$(function () {
$('#selection1').change(function () {
localStorage.setItem('todoData', this.value);
});
if (localStorage.getItem('todoData')) {
$('#selection1').val(localStorage.getItem('todoData')).trigger('change');
}
});
$(function () {
$('#selection2').change(function () {
localStorage.setItem('todoData2', this.value);
});
if (localStorage.getItem('todoData2')) {
$('#selection2').val(localStorage.getItem('todoData2')).trigger('change');
}
});
$(function () {
$('#selection3').change(function () {
localStorage.setItem('todoData3', this.value);
});
if (localStorage.getItem('todoData3')) {
$('#selection3').val(localStorage.getItem('todoData3')).trigger('change');
}
});
$(function () {
$('#selection4').change(function () {
localStorage.setItem('todoData4', this.value);
});
if (localStorage.getItem('todoData4')) {
$('#selection4').val(localStorage.getItem('todoData4')).trigger('change');
}
});
$(function () {
$('#selection5').change(function () {
localStorage.setItem('todoData5', this.value);
});
if (localStorage.getItem('todoData5')) {
$('#selection5').val(localStorage.getItem('todoData5')).trigger('change');
}
});
$(function () {
$('#selection6').change(function () {
localStorage.setItem('todoData6', this.value);
});
if (localStorage.getItem('todoData6')) {
$('#selection6').val(localStorage.getItem('todoData6')).trigger('change');
}
});
$(function () {
$('#selection7').change(function () {
localStorage.setItem('todoData7', this.value);
});
if (localStorage.getItem('todoData7')) {
$('#selection7').val(localStorage.getItem('todoData7')).trigger('change');
}
});
$(function () {
$('#selection8').change(function () {
localStorage.setItem('todoData8', this.value);
});
if (localStorage.getItem('todoData8')) {
$('#selection8').val(localStorage.getItem('todoData8')).trigger('change');
}
});
$(function () {
$('#selection9').change(function () {
localStorage.setItem('todoData9', this.value);
});
if (localStorage.getItem('todoData9')) {
$('#selection9').val(localStorage.getItem('todoData9')).trigger('change');
}
});
$(function () {
$('#selection10').change(function () {
localStorage.setItem('todoData10', this.value);
});
if (localStorage.getItem('todoData10')) {
$('#selection10').val(localStorage.getItem('todoData10')).trigger('change');
}
});
$(function () {
$('#selection11').change(function () {
localStorage.setItem('todoData11', this.value);
});
if (localStorage.getItem('todoData11')) {
$('#selection11').val(localStorage.getItem('todoData11')).trigger('change');
}
});
$(function () {
$('#selection12').change(function () {
localStorage.setItem('todoData12', this.value);
});
if (localStorage.getItem('todoData12')) {
$('#selection12').val(localStorage.getItem('todoData12')).trigger('change');
}
});
$(function () {
$('#selection13').change(function () {
localStorage.setItem('todoData13', this.value);
});
if (localStorage.getItem('todoData13')) {
$('#selection13').val(localStorage.getItem('todoData13')).trigger('change');
}
});
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="pieteicejs.js"></script>
</head>
<select id="selection1">
<option>1</option>
<option>2</option>
<option>3</option>
</select><br></br>
<select id="selection2">
<option>4</option>
<option>5</option>
<option>6</option>
</select><br></br>
<select id="selection3">
<option>7</option>
<option>8</option>
<option>9</option>
</select><br></br>
<select id="selection4">
<option>10</option>
<option>11</option>
<option>12</option>
</select><br></br>
<select id="selection5">
<option>13</option>
<option>14</option>
<option>15</option>
</select><br></br>
<select id="selection6">
<option>16</option>
<option>17</option>
<option>18</option>
</select><br></br>
<select id="selection7">
<option>19</option>
<option>20</option>
<option>21</option>
</select><br></br>
<select id="selection8">
<option>22</option>
<option>23</option>
<option>24</option>
</select><br></br>
<select id="selection9">
<option>25</option>
<option>26</option>
<option>27</option>
</select><br></br>
<select id="selection10">
<option>28</option>
<option>29</option>
<option>30</option>
</select><br></br>
<select id="selection11">
<option>31</option>
<option>32</option>
<option>33</option>
</select><br></br>
<select id="selection12">
<option>34</option>
<option>35</option>
<option>36</option>
</select><br></br>
<select id="selection13">
<option>37</option>
<option>38</option>
<option>39</option>
</select><br></br>
"How can I separate drop down menu from each other in order so they both save in Localstorage"
"How can I separate drop down menu from each other in order so they both save in Localstorage"
"How can I separate drop down menu from each other in order so they both save in Localstorage"

LocalStorage is basically a key - value storage, for more information read this at MDN
// Assuming you have a clear localStorage...
localStorage.getItem('score') // -> null
// The first setItem will create a new entry
localStorage.setItem('score', 5)
localStorage.getItem('score') // -> 5
// Any next setItem on the same key will overwrite the data
localStorage.setItem('score', 10)
localStorage.getItem('score') // -> 10
So, if you want to save both dropdowns separate, you will have to use different names, e.g.
// SELECT 1
localStorage.setItem('todoData1', this.value);
localStorage.getItem('todoData1');
// SELECT 2
localStorage.setItem('todoData2', this.value);
localStorage.getItem('todoData2');
Edit: (after question change)
To achieve this for a list of selects, you might prefer declaring that using a loop:
$(function() {
for (let i = 0; i < 13; i++) {
const storageName = `todoData${i}`;
const selectionId = `#selection${i}`;
$(selectionId).change(function() {
localStorage.setItem(storageName, this.value);
});
// to save data initially
if (!localStorage.getItem(storageName)) {
$(selectionId).trigger('change');
}
}
});

Related

response.writeHead(302) in NodeJS not redirecting in async function callback

Below is a snippet of my NodeJS server code.
async function handleLoginReq(req, res) {
let queryDB = `
SELECT password FROM faculty_information
WHERE email='${userInfo["user-email"]}';
`;
try {
const dbres = await client.query(queryDB);
if (dbres.rows.length !== 0) {
if (dbres.rows[0].password === '') {
const errVal = 'Please register yourself correctly';
res.writeHead(302, {
'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`
});
res.end();
client.end();
} else if (userInfo["user-password"] === dbres.rows[0].password) {
res.writeHead(302, {
'Location': '/experiment_page/index.html'
});
res.end();
client.end();
} else {
const errVal = 'Incorrect password or email address';
res.writeHead(302, {
'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`
});
res.end();
client.end();
}
} else {
const errVal = 'Please sign up';
console.log(errVal);
res.statusCode(302);
res.setHeader('Location', `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`)
//res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} catch (err) {
res.writeHead(500);
res.end("Internal server error");
client.end();
}
}
handleLoginReq(req, res);
The client.query() function is a asynchronous function. However, none of the res.writeHead(302)'s are working inside the callback of this function. A res.writeHead(302) does work if I add it below the function call of handleLoginReq(req, res);.
handleLoginReq(req, res);
// Below redirect works
res.writeHead(302, { 'Location': '/experiment_page/index.html' });
res.end();
The above code runs when a form is submitted on /login_page/loginPage.html.
Instead of redirecting the user to either /experiment_page/index.html or back to /login_page/loginPage.html?error=something with a URL parameter, it just reloads the page to /login_page/loginPage.html.
Below is the HTML for this page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/login_page/css/loginStyles.css">
<script src="/login_page/js/labelChange.js" defer></script>
<script src="/login_page/js/redirectSignUp.js" defer></script>
<script src="/login_page/js/loginValidation.js" defer></script>
<title>DigiChit - The Online Chit System | Login</title>
</head>
<body>
<nav class="navbar">
<ul>
<li><h1>DigiChit</h1></li>
<li>Home</li>
<li>About</li>
</ul>
</nav>
<div class="login-info">
<form method="POST" class="form">
<img src="/images/avatar.png" id="avatar" alt="avatar">
<h2>Login</h2>
<div class="input-group">
<input type="email" name="user-email" id="user-email" required>
<label for="user-email">Email</label>
<span id="email-error"></span>
</div>
<div class="input-group">
<input type="password" name="user-password" id="user-password" required>
<label for="user-password">Password</label>
<span id="general-error"></span>
<button type="submit" class="submit-btn" id="login-button">Login</button>
<button type="submit" class="submit-btn" id="sign-up">SignUp</button>
Forgot Password?
</div>
</form>
</div>
</body>
</html>
None of the client side JS scripts are interfering with the process either. I did put console.log()'s in all of the other conditions, and there are no clashes either where many res.writeHead() are running simultaneously.
If anyone can find why this is happening?
I tried to use res.setHeader() and res.statusCode() instead of res.writeHead() to see if anything changed, and nothing happened. I tried using promises instead of async/await and that changed nothing either.
###################################
EDIT (Updated with async/await syntax)
###################################
Here is the server code snippet containing more info on where the function is located.
const server = https.createServer(options, async function (req, res) {
// For form submissions
if (req.method.toLowerCase() === "post") {
let body = '';
req.on("data", (chunk) => {
body += chunk.toString();
})
req.on("end", async function () {
// querystring.decode converts browser query string into an object
const userInfo = querystring.decode(body); // userInfo is an object here
// Status code 302 stands for code of redirection
if (req.url.startsWith("/login_page/loginPage.html")) {
const client = createClient();
await client.connect();
let errVal = "";
async function handleLoginReq(req, res) {
// Below is the query to get user password
let dbQuery = `
SELECT password FROM faculty_information
WHERE email='${userInfo["user-email"]}';
`;
try {
const dbres = await client.query(dbQuery);
if (dbres.rows.length !== 0) {
if (dbres.rows[0].password === '') {
const errVal = 'Please register yourself correctly';
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
} else if (userInfo["user-password"] === dbres.rows[0].password) {
res.writeHead(302, { 'Location': '/experiment_page/index.html' });
res.end();
client.end();
} else {
const errVal = 'Incorrect password or email address';
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} else {
const errVal = 'Please sign up';
console.log(errVal);
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} catch (err) {
res.writeHead(500);
res.end("Internal server error");
client.end();
}
}
await handleLoginReq(req, res);

Vue3 Object - than is not a function

I have a problem with my slider on vue3:
SlideShow
<template>
<div class="slides-wrapper">
<button
class="btn btn-primary btn-action btn-lg slides-prev"
#click="changePhoto(-1)"
:disabled="prevBtn">
<i class="icon icon-arrow-left"></i>
</button>
<div class="slides">
<Slide
:url="activeUrl"
:text="infoSlides"/>
</div>
<button
class="btn btn-primary btn-action btn-lg slides-next"
#click="changePhoto(+1)"
:disabled="nextBtn">
<i class="icon icon-arrow-right"></i>
</button>
</div>
</template>
<script>
import { ref, computed } from 'vue';
import Slide from './Slide.vue';
import { loader } from '#/helpers/loader';
export default {
name: 'SlideShow',
components: {
Slide,
},
props: {
images: {
type: Array,
},
},
setup(props) {
const numberPhoto = ref(0);
const lenghtTablePhotos = ref(+props.images.length - 1);
const activeUrl = computed(() => props.images[numberPhoto.value].url);
const nextBtn = computed(() => numberPhoto.value === lenghtTablePhotos.value);
const prevBtn = computed(() => numberPhoto.value === 0);
const infoSlides = computed(() => `${numberPhoto.value + 1}/${lenghtTablePhotos.value + 1}`);
function changePhoto(param) {
const index = numberPhoto.value + param;
const slide = props.images[index];
if (slide !== undefined) {
loader(props.images[index].url)
.than((url) => console.log(url))
.catch(console.log('err'));
}
}
return {
numberPhoto,
activeUrl,
lenghtTablePhotos,
changePhoto,
nextBtn,
prevBtn,
infoSlides,
};
},
};
</script>
<style lang="scss" scoped>
.slides-wrapper {
width: 500px;
position: relative;
}
.slides-next,
.slides-prev {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.slides-prev {
left: 0;
}
.slides-next {
right: 0;
}
</style>
and my js file:
loader.js
export function loader(url) {
const img = document.createElement('img');
return new Promise((resolve, reject) => {
// eslint-disable-next-line no-unused-vars
img.onload = () => resolve(url);
img.onerror = () => reject(url);
img.src = url;
});
}
but it doesnt work, can someone help ?
enter image description here
you have to use reactive on your variable to use Composition API,
u can access
https://v3.vuejs.org/api/basic-reactivity.html#reactive
you have a typo at calling the .then function. You wrote than instead of then!

How to fix "Can't perform a React state update on an unmounted component"?

I'm building a TODO list and one of the things that it needs to do is delete.
Here is my server.js code
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const cpdRoutes = express.Router();
const PORT = 4000;
let Cpd = require("./cpd.model");
app.use(cors());
app.use(bodyParser.json());
//connects my backend to my mongo database
mongoose.connect('mongodb://127.0.0.1:27017/cpds', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})
cpdRoutes.route('/').get(function(req, res) {
Cpd.find(function(err, cpds) {
if (err) {
console.log(err);
}
else {
res.json(cpds);
}
});
});
//finds the data by id
cpdRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Cpd.findById(id, function(err, cpd) {
res.json(cpd);
});
});
//creating data
cpdRoutes.route('/add').post(function(req, res) {
let cpd = new Cpd(req.body);
cpd.save()
.then(cpd => {
res.status(200).json({'cpd': 'New data added successfully'});
})
.catch(err => {
res.status(400).send('Adding new data failed');
});
});
//update data
cpdRoutes.route('/update/:id').post(function(req, res) {
Cpd.findById(req.params.id, function(err, cpd) {
if (!cpd)
res.status(404).send("data is not found");
else
cpd.cpd_date = req.body.cpd_date;
cpd.cpd_activity = req.body.cpd_activity;
cpd.cpd_hours = req.body.cpd_hours;
cpd.cpd_learningStatement = req.body.cpd_learningStatement;
cpd.save().then(cpd => {
res.json('Data updated!');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
// cpdRoutes.route('/delete/:id').post(function(req, res) {
// Cpd.findById(req.params.id, function(err, cpd) {
// if (!cpd)
// res.status(404).send("data is not found");
// else
// cpd.cpd_date = req.body.cpd_date;
// cpd.cpd_activity = req.body.cpd_activity;
// cpd.cpd_hours = req.body.cpd_hours;
// cpd.cpd_learningStatement = req.body.cpd_learningStatement;
// cpd.save().then(cpd => {
// res.json('Data updated!');
// })
// .catch(err => {
// res.status(400).send("Update not possible");
// });
// });
// });
cpdRoutes.route.get('/delete', function(req, res){
var id = req.query.id;
Cpd.find({_id: id}).remove().exec(function(err, expense) {
if(err)
res.send(err)
res.send('Data successfully deleted!');
})
});
app.use('/cpds', cpdRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
My delete component:
import React from 'react';
import axios from 'axios';
import { Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
class DeleteCpd extends React.Component {
constructor(){
super();
this.state={id:''};
this.onClick = this.onClick.bind(this);
this.delete = this.delete.bind(this);
}
// componentDidMount() {
// this.setState({
// id: this.props.cpds.id
// })
// }
componentDidMount() {
axios.get('http://localhost:4000/cpds/'+this.props.match.params.id)
.then(response => {
this.setState({
cpd_date: response.data.cpd_date,
cpd_activity: response.data.cpd_activity,
cpd_hours: response.data.cpd_hours,
cpd_learningStatement: response.data.cpd_learningStatement
})
})
.catch(function (error) {
console.log(error);
})
}
onClick(e){
this.delete(this);
}
delete(e){
axios.get('http://localhost:4000/cpds/'+this.props.match.params.id)
.then(function(response) {
});
}
render(){
return (
<Button onClick={this.onClick}>
<Link to={{pathname: '/', search: '' }} style={{ textDecoration: 'none' }}>
<span className="glyphicon glyphicon-remove"></span>
</Link>
</Button>
)
}
}
export default DeleteCpd;
and my App.js:
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import CreateCpd from "./components/create-cpd.component";
import EditCpd from "./components/edit-cpd.component";
import CpdsList from "./components/cpds-list.component";
import DeleteCpd from "./components/cpds-delete.component";
class App extends Component {
render() {
return (
<Router>
<div className="container">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<Link to="/" className="navbar-brand">MERN-Stack Cpd tracker App</Link>
<div className="collpase navbar-collapse">
<ul className="navbar-nav mr-auto">
<li className="navbar-item">
<Link to="/" className="nav-link">Data List</Link>
</li>
<li className="navbar-item">
<Link to="/create" className="nav-link">Create Cpd data</Link>
</li>
</ul>
</div>
</nav>
<br/>
<Route path="/" exact component={CpdsList} />
<Route path="/edit/:id" component={EditCpd} />
<Route path="/delete/:id" component={DeleteCpd} />
<Route path="/create" component={CreateCpd} />
</div>
</Router>
);
}
}
export default App;
This is the error my getting:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in CpdList (created by Context.Consumer)
What I'm trying to do is delete via id. What am I doing wrong?
This is my CPDList:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
// import { CSVLink } from "react-csv";
// import DeleteCpd from './cpd_delete.component';
const Cpd = props => (
<tr>
<td>{props.cpd.cpd_date}</td>
<td>{props.cpd.cpd_activity}</td>
<td>{props.cpd.cpd_hours}</td>
<td>{props.cpd.cpd_learningStatement}</td>
<td>{props.cpd.cpd_evidence}</td>
<td>
<Link to={"/edit/"+props.cpd._id}>Edit</Link>
</td>
<td>
<Link to={"/delete/"+props.cpd._id}>Delete(not working yet)</Link>
</td>
</tr>
)
export default class CpdList extends Component {
constructor(props) {
super(props);
this.state = {
cpds: [],
// csvData:[
// {
// "date": ""
// },
// {
// "activity": ""
// },
// {
// "hours": ""
// },
// {
// "learningStatement": ""
// },
// {
// "evidence": ""
// }
// ]
};
};
// exportCsv()
// {
// var csvRow=[];
// }
componentDidMount() {
axios.get('http://localhost:4000/cpds/')
.then(response => {
this.setState({ cpds: response.data });
})
.catch(function (error){
console.log(error);
});
};
componentDidUpdate() {
axios.get('http://localhost:4000/cpds/')
.then(response => {
this.setState({ cpds: response.data });
})
.catch(function (error){
console.log(error);
});
}
cpdList() {
return this.state.cpds.map(function(currentCpd, i){
return <Cpd cpd={currentCpd} key={i} />;
});
}
render() {
return(
<div>
<h3>Cpd Data List</h3>
<table className="table table-striped" style={{ marginTop: 20 }} >
<thead>
<tr>
<th>Date</th>
<th>Activity</th>
<th>Hours</th>
<th>Learning Statement</th>
<th>Evidence</th>
</tr>
</thead>
<tbody>
{ this.cpdList() }
</tbody>
</table>
{/* <CSVLink data={csvData}
filename={"db.csv"}
color="primary"
style={{float: "left", marginRight: "10px"}}
className="btn btn-primary"
>Download .CSV
</CSVLink> */}
</div>
)
}
};
please ignore the commented out code still working on that.

react - expose component function

How do I access in React, a method of one component in other components, that are not in a direct parent-child relation? For example:
var QuestionsBox = React.createClass({
**editQuestion**: function(questionId){
// do something
// this.refs.mainForm.loadQuestionFromServer.bind(this, questionId);
},
getInitialState: function() {
return {data: []};
},
render: function() {
return (
<div className="questionsBox">
<h4>Questions</h4>
<QuestionsList data={this.state.data}/>
</div>
);
}
});
var QuestionsList = React.createClass({
render: function() {
var reactObject = this;
var questionsList = this.props.data.map(function (question) {
return (
<Question id={question.id}>
{question.question_name}
</Question>
);
});
return (
<div>
{questionsList}
</div>
);
}
});
var Question = React.createClass({
render: function() {
return(
<div className="question">
{this.props.children}
<a onClick={**access here editQuestion method of QuestionsBox component, with parameters**}>edit</a>
</div>
);
}
});
or other similar structures, that do not have a direct parent-child relation..
You need to pass it down as a prop
var QuestionsBox = React.createClass({
**editQuestion**: function(questionId){
// do something
// this.refs.mainForm.loadQuestionFromServer.bind(this, questionId);
},
getInitialState: function() {
return {data: []};
},
render: function() {
return (
<div className="questionsBox">
<h4>Questions</h4>
<QuestionsList
data={this.state.data}
editQuestion={this.editQuestion}
/>
</div>
);
}
});
var QuestionsList = React.createClass({
render: function() {
var reactObject = this;
var questionsList = this.props.data.map(function (question) {
return (
<Question>
id={question.id}
editQuestion={this.props.editQuestion}
{question.question_name}
</Question>
);
});
return (
<div>
{questionsList}
</div>
);
}
});
var Question = React.createClass({
render: function() {
return(
<div className="question">
{this.props.children}
<a id={this.props.id} onClick={this.editQuestion}>edit</a>
</div>
);
},
editQuestion: function(e) {
this.props.editQuestion(e.target.id);
}
});
Create a separate storage class. Embed the instance of that class in each place that has access to editing the data it contains. You see this in Flux, Facebook's architecture library. Instead of passing down handlers, have the events be emitted from the Storage class, and have each component subscribe to that instance of the storage class.
It's hard to describe, but that link has a video which will make it very clear. This way, any time data changes the store will trigger events which will trigger re-renders of your react views.

Dynamic rooms with Socket.io and Node

I'm trying to use the new "room" feature in Socket.io v.7 to create dynamic chat rooms, but I'm having problems getting static rooms to work in my example. Based on the URL the user selects they should end up in room1 or room2. Anything the user enters in the chat should be broadcast to users in the same room. I have 2 browsers (chrome & ff) each with a tab open to /room1 and /room2, however nothing I type in seems to be broadcast to the other tabs. What am I doing wrong?
Server code
var app = require('express').createServer();
var io = require("socket.io").listen(app);
io.sockets.on('connection', function (socket) {
// join to room and save the room name
socket.on('join room', function (room) {
socket.set('room', room, function() { console.log('room ' + room + ' saved'); } );
socket.join(room);
})
socket.on('message', function(data) {
console.log("Client data: " + data);
// lookup room and broadcast to that room
socket.get('room', function(err, room) {
//room example - https://github.com/learnboost/socket.io
// neither method works for me
socket.broadcast.to(room).emit('new fan');
io.sockets.in(room).emit('new non-fan');
})
})
});
app.get('/room1', function(req, res){
res.render('example2-client.ejs', {layout:false});
});
app.get('/room2', function(req, res){
res.render('example2-client-2.ejs', {layout:false});
});
app.listen(4000);
Client code room 1
<!DOCTYPE HTML>
<html><head>
<title>Code review for Snipet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('http://localhost:4000');
$("#msgbox").keypress( function(event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});
socket.on('connect', function (data) {
socket.emit('join room', 'room1' );
});
socket.on('message', function (data) {
add_message(data);
});
function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("<BR>");
}
function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('message', r );
add_message(r);
$("#msgbox").val('');
}
});
</script>
</head>
<body>
<div id="chat" style="height: 200px; width: 200px; border: 1px solid grey;">
<div id="chatlog" style="height: 178px; width: 200px; overflow-y: scroll;"></div>
<input type="text" id="msgbox" style="margin-left: 2px; width: 193px;">
</div>
</body>
</html>
Client code 2
<!DOCTYPE HTML>
<html><head>
<title>Code review for Snipet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('http://localhost:4000');
$("#msgbox").keypress( function(event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});
socket.on('connect', function (data) {
socket.emit('join room', 'room2' );
});
socket.on('message', function (data) {
add_message(data);
});
function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("<BR>");
}
function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('message', r );
add_message(r);
$("#msgbox").val('');
}
});
</script>
</head>
<body>
<div id="chat" style="height: 200px; width: 200px; border: 1px solid grey;">
<div id="chatlog" style="height: 178px; width: 200px; overflow-y: scroll;"></div>
<input type="text" id="msgbox" style="margin-left: 2px; width: 193px;">
</div>
</body>
</html>
You don't seem to be listening to these events
socket.broadcast.to(room).emit('new fan');
io.sockets.in(room).emit('new non-fan');
on the client side you need:
socket.on('new fan', function (data) {
console.log('new fan');
});
You're also not sending the message to the clients.
Inside:
socket.on('message', function(data) { })
on the server, you need to do :
io.sockets.in(room).emit('message', data);

Resources