I want to send select box value to my NodeJS server with onchange() function using socket.io.
Now, I can send with button as below codes show;
server.js;
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
socket.on('socketdeneme', function(msg) {
console.log("Message received: " + msg);
});
});
http.listen(2000, function() {
console.log('listening on *:2000');
});
index.html;
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function () {
var socket = io();
$('form').submit(function() {
socket.emit('socketdeneme', $('#m').val());
});
});
</script>
</head>
<body>
<form action="">
<select id=m multiple>
<option value="dnm">dnm</option>
<option value="dnm1">dnm1</option>
<option value="dnm2">dnm2</option>
</select>
<button>Send</button>
</form>
</body>
</html>
On the other hand, below code send data with onchange() function but I couldn't use it with socket.io.
<script type="text/javascript">
function submitformfabrika() {
document.formsubmitfabrika.submit();
}
</script>
You can use the .change method (https://api.jquery.com/change/) to emit your socketdeneme event which will be received by the server.
Replace
$('form').submit(function() {
socket.emit('socketdeneme', $('#m').val());
});
with
$('form').change(function() {
socket.emit('socketdeneme', $('#m').val());
});
Related
I have created a index.js which loads index.html using sockets.
the server is running successfully and also the index.html page loads. but cant append the written text in the div.
index.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000, function() {
console.log("SERVER CREATED WITH PORT 3000");
});
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send', function(data) {
io.sockets.emit('new', data);
});
});
index.html
<html>
<head>
<title>chat</title>
<style>
#chat {
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input id="message" />
<input type="submit" />
</form>
<h1>Working</h1>
<script src="jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($) {
var socket = io.connect();
var $messageform = $('#send-message');
var $messagebox = $('#message');
var $chat = $('#chat');
$messageform.submit(function(e) {
e.preventDefault();
socket.emit('send', $messagebox.val());
$messagebox.val('');
});
socket.on('new', function(data) {
$chat.append(data + "<br />");
});
});
</script>
</body>
</html>
These are the files which I have created and want to send the text to all tabs.
The browser just gets refreshed without loading the text when submit is hit.
Please let me know what I am doing wrong.
index.js
var app = require('express')();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
server.listen(process.env.PORT || 3000);
app.use(require('express').static(path.join(__dirname)));
console.log('server running');
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', data);
});
});
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
When I start up the server, the console logs "server running" fine. I can't get the submit post button to do anything. None of the debug console messages appear and nothing happens. It's supposed to emit "new post" when the submit button is clicked but it looks as if nothing goes through
I was able to get your code to work on my own computer like this:
index.js
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(express.static(__dirname));
console.log('server running');
io.on('connection', function (socket) {
console.log("connection");
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', post);
});
});
server.listen(process.env.PORT || 3000);
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="/client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
Changes to index.js
Define express variable so it can be reused.
Define app.get() before app.use(express.static(...)) so we're sure to serve index.html with the app.get() and not from the static location.
Change res.sendfile() to res.sendFile()`
Change socket.emit("posted", data) to socket.emit("posted", post).
Move server.listen() to end after everything else is set up.
Remove path.join() from express.static() call since it is not needed there.
Add path.join() to res.sendFile() call for cross platform safety in path building.
Of these, the only one I'm sure was causing an error was #4, the others are good housekeeping.
Changes to client.js
None
Changes to index.html
Change path to client.js to /client.js.
If this code doesn't work on heroku, then you either don't have files positioned in the right directories or heroku is not configured properly to allow your app or socket.io to work properly. If I were you, I would first verify that this code work on your own local computer and only then, go try it on heroku to eliminate variables first.
I was trying to implement Quill API with socket.io to build a realtime editor. I was able to get the Delta emitted, but quill.updateContents() does not seems to update the text editor with the emitted Delta op data.
Here is my code:
index.html (client side)
<!DOCTYPE html>
<html>
<head>
<title>Connected Clients</title>
<!--<meta charset="UTF-8"> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--<script type="text/javascript" src="jquery.js"></script> -->
<script src="/socket.io/socket.io.js"></script>
<link href="https://cdn.quilljs.com/1.1.1/quill.snow.css" rel="stylesheet">
<link href="https://cdn.quilljs.com/1.1.2/quill.snow.css" rel="stylesheet">
</head>
<body>
<div id="editor">
<p>Hello World!</p>
<p>Some initial <strong>bold</strong> text</p>
<p><br></p>
</div>
<span id="insertHere"></span>
<script src="https://cdn.quilljs.com/1.1.2/quill.js"></script>
<script>
$(document).ready(function () {
var quill = new Quill('#editor', {
theme: 'snow'
});
var socket = io();
socket.on('updated_para',function(data){
var el = document.getElementById('insertHere');
el.innerHTML = data;
var ops = data;
quill.updateContents(data);
});
quill.on('text-change', function(delta, source) {
var para = quill.getContents();
socket.emit('para',{delta:JSON.stringify(delta.ops)});
});
});
</script>
</body>
</html>
index.js (server side)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.sockets.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('para',function(data){
io.emit('updated_para',data.delta);
console.log('message: ' + data.delta);
});
});
I will really appreciate your help!
i think you forget to convert the json code back to an object..
you convert the data before sending to your socket server to a json string. So the date you receive would alway be a string instead of an json.object.
// Replace
var ops = data;
quill.updateContents(data);
// with
var ops = JSON.parse(data);
quill.updateContents(data);
i'm planning to make a similar kind of editor, so i can watch / share code editing.
Kind Regard.
I was trying my hands on Socket.io.
I have the following code.
This is my index.html.
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello(){
var msg = document.getElementById('m');
console.log(msg); <- This is getting printed.
socket.emit('message', msg.value);
msg.value='';
return (false);
}
// $('form').submit(function(){
// socket.emit('chat message', $('#m').val());
// $('#m').val('');
// return false;
// });
// socket.on('chat message', function(msg){
// $('#messages').append($('<li>').text(msg));
// });
</script>
</body>
</html>
This is my server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("GO!") <- This is getting printed
socket.on('chat message', function(msg){
console.log(msg); <- This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
I have cloned the sample project from the Socket.io website. I was trying to modify some code by replacing the Jquery with VanillaJS.
You are listening for chat message but emitting message from client. Event name provided with .emit must match with the event name being listened on the server in .on handler.
//SERVER SIDE CODE
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("GO!") < -This is getting printed
socket.on('chat message', function(msg) {
console.log(msg); < -This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function() {
console.log('listening on *:3001');
});
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" />
<button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello() {
var msg = document.getElementById('m');
console.log(msg); < -This is getting printed.
socket.emit('chat message', msg.value);
//-----------^^^^^^^^^^^^ Event name must match with the `.on` listener on the server!
msg.value = '';
return (false);
}
</script>
</body>
</html>
Please I have this small demo of a collaborative editor in a pub/sub fashion.
Scenario:
Server :S
Clients : A, B
A sends text S.
S receives text and brodcast to B.
B sends text to S.
S receives text and brodcast to A, A receive text, but document.getElementById is not updting the display.
I suspect the problem is with javascript execution order...
I am bit confused, can someone points me what goes wrong with my client ?
Server:
var app = require('express')();
var http = require('http').createServer(app)
var io = require('socket.io').listen(http);
//Server accepting connect on this port
http.listen(3000);
//Establishing connection to client and disconnecting
io.sockets.on('connection', function(socket){
console.log('Connected to a new client');
socket.on('room', function(room) {
socket.join(room);
console.log('join room '+ room);
});
socket.on('disconnect', function(){
socket.disconnect();
console.log('Disconnected from a client');
});
var room= 'room1';
//Data exchange between client and server
//Server receives new data from a client and broadcast it to others
socket.on('client_character',function(msg){
//receive data
console.log('Data from client'+msg.buffer);
socket.in(room).broadcast.emit('server_character',msg.buffer);
//socket.broadcast.to(room).emit('server_character', msg.buffer);
//socket.to(room).emit('server_character',msg.buffer);
});
});
Client:
Run separately on Apache server
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Client</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<link rel="stylesheet" type="text/css" href="styles/style.css">
</head>
<body>
<textarea id="notepad"></textarea><br/>
<script>
$(function () {
var socket = io.connect('http://localhost:3000',
{'sync disconnect on unload':false});
var room = "room1";
socket.on('connect', function() {
socket.emit('room', room);
});
//receive character from server
socket.on('server_character',function(content){
console.log('From Server:'+ content);
document.getElementById('notepad').innerHTML=content;
});
//For each typed character
$('#notepad').on('keypress',function(){
var character= $('#notepad').val();
//send character to servers
socket.emit('client_character',{buffer:character});
console.log('To Server:'+ {buffer:character} );
});
});
</script>
</body>
</html>
style.css:
#notepad{
height:500px;
width:500px;
font-size: 14px;
color: brown;
}
package.json:
{
"name": "collaborative",
"version": "0.0.1",
"description": "none",
"dependencies": {
"express": "^4.10.2",
"socket.io": "^1.4.5"
}
}
Reference Demo:
[https://www.youtube.com/watch?v=I0iikz1F1Lk][1]
I did some thanges in tour code for fix one bug in input and add more logs and this is working here with FF and Chrome ( i dont have IE here )
Server:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io').listen(http);
//Server accepting connect on this port
http.listen(3000);
//Establishing connection to client and disconnecting
io.sockets.on('connection', function(socket){
console.log('Connected to a new client');
socket.on('error', function(err) {
//here i change options
console.log('Error!', err);
});
socket.on('room', function(room) {
socket.join(room);
console.log('join room: '+ room);
});
socket.on('disconnect', function(){
// socket.disconnect();
console.log('Disconnected from a client');
});
var room= 'room1';
//Data exchange between client and server
//Server receives new data from a client and broadcast it to others
socket.on('client_character',function(msg){
//receive data
console.log('Data from client: '+msg.buffer);
socket.in(room).broadcast.emit('server_character',msg.buffer);
//socket.broadcast.to(room).emit('server_character', msg.buffer);
//socket.to(room).emit('server_character',msg.buffer);
});
});
Client:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Client</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<link rel="stylesheet" type="text/css" href="styles/style.css">
</head>
<body>
<textarea id="notepad"></textarea><br/>
<script>
$(function () {
var socket = io.connect('http://localhost:3000',
{'sync disconnect on unload':false});
var room = "room1";
socket.on('connect', function() {
socket.emit('room', room);
});
//receive character from server
socket.on('server_character',function(content){
console.log('From Server:'+ content);
document.getElementById('notepad').innerHTML=content;
});
//For each typed character
$('#notepad').on('keyup',function(){
var character= $('#notepad').val();
//send character to servers
socket.emit('client_character', {buffer:character});
console.log('To Server:', { buffer:character } );
});
});
</script>
</body>
</html>