Socket.io is not defined - javascript

Whenever I go to http://localhost:8080/search (search.html), it loads all of the html, then it reaches the client-side javascript and crashes. The first console.log in searchClient.js works, but not the second. The error is that io is not defined.
server.js:
var http = require('http');
var express = require('express');
var anyDB = require('any-db');
var engines = require('consolidate');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var conn = anyDB.createConnection('sqlite3://riverdata.db');
app.engine('html', engines.hogan);
app.set('views', __dirname + '/templates');
app.use(express.static(__dirname + '/public'));
app.get("/", function(request, response){
response.render('home.html');
});
app.get("/search", function(request, response){
response.render('search.html');
});
io.on('connection', function(socket){
socket.on('join', function(){
});
socket.on('search', function(toShowList, conditionsList){
var data = conn.query('SELECT toShowList FROM riverdata WHERE conditionsList');
console.log("im in socket.on(search)");
socket.emit('data', data);
});
socket.on('disconnect', function(){
});
});
app.listen(8080);
searchClient.js:
console.log("begins");
var socket = io.connect();
console.log("keeps running");
window.addEventListener('load', function(){
console.log("page loads");
var search = document.getElementById("searchButton");
submit.addEventListener("click", search, false);
socket.emit('join');
socket.on('data', function(data){
console.log(data);
})
}, false);
function search(){
console.log("button clicked");
var toShowList = [];
var conditionsList = [];
socket.emit('search', toShowList, conditionsList);
}
search.html:
<!DOCTYPE HTML PUBLIC>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src='localhost:8080/socket.io/socket.io.js'></script>
<script type="text/javascript" src="/searchClient.js"></script>
<title>Envirostats Database</title>
<link rel="stylesheet" href="/style.css" type="text/css" />
</head>
<body class="search">
<form action="">
<input type="checkbox" name="data" value="data"> Show Date <br>
<input type="checkbox" name="data" value="river"> Show River <br>
</form>
<button id=searchButton> Search </button>
</body>
</html>

Related

Button is not found in HTML

All I'm working on a small game using node js, so I have a button and when I press the button a rectangle should be drawn in the canvas that is present on my Html page.
But I think my node js is loading faster than my Html, how can I make all my Html elements load and then node js execute.
Here is my code
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sanke Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button type="submit" id = "smallButton" name="button">Draw</button>
<canvas id="canvas" tabindex="0" width="640" height="480"></canvas>
<script src="userInput.js"></script>
<script src="snake.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
snake.js
const gameBoard = document.getElementById("canvas");
const gameBoard_ctx = canvas.getContext("2d");
const bun = document.getElementById("smallButton");
//Generating Random Coordinate
function randomCoordinates(){
var startX = 40+Math.random()*560;
var startY = 40+Math.random()*400;
return [startX, startY];
}
// Drawing snake
function drawSnakePart(snakePart){
gameBoard_ctx.fillStyle = 'lightblue';
gameBoard_ctx.strokestyle = 'darkblue';
gameBoard_ctx.fillRect(snakePart[0], snakePart[1], 10, 10);
gameBoard_ctx.strokeRect(snakePart[0], snakePart[1], 10, 10)
}
function drawSnake(){
for(var i=0; i<8; i++){
drawSnakePart(randomCoordinates());
}
}
bun.addEventListener("click", function(){
alert("clicked");
drawSnake();
})
app.js
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
//Responding to Root request
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html")
})
//Responds if client request is made
app.get("/client.js", function(req, res){
res.sendFile(__dirname + "/client.js");
})
//Responds to css req
app.get("/styles.css", function(req, res){
res.sendFile(__dirname + "/styles.css");
})
//Responds to keyMovements
app.get("/userInput.js", function(req, res){
res.sendFile(__dirname+"/userInput.js");
})
app.get("/snake.js", function(req, res){
res.sendFile(__dirname+"/snake.js");
})
io.on('connection', function(socket){
console.log("User is connected");
socket.on("disconnect", function(){
console.log("User Disconnected");
})
socket.emit("serverToClient", "Hello World");
socket.on("clientToServer", function(event){
console.log(event);
})
socket.on("clientToClient", data => {
socket.broadcast.emit("serverToClient", data);
})
})
server.listen(3000, function(){
console.log("Listening to port 3000");
})

Client print 'Undefined' messag when i send json info from the server

When I click "ajaxsend" button, the result shows "undefined" on the console.
how can I check that function res.json is working fine?
app.js
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.listen(3000, function() {
console.log("start!! express server on port 3000");
});
app.use(express.static('public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.post ('/ajax_send_email', function(req, res){
console.log(req.body.email)
var responseData = {'result':'ok','email':req.body.email}
console.log(responseData)
res.json(responseData)
});
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
<title>email form</title>
</head>
<body>
<form action="/email_post" method="post">
email : <input type="text" name="email"><br/>
submit <input type="submit">
</form>
<button class="ajaxsend">ajaxsend</button>
<div class="result"></div>
<script>
document.querySelector('.ajaxsend').addEventListener('click',function(){
var inputdata = document.forms[0].elements[0].value;
sendAjax('http://127.0.0.1:3000/ajax_send_email',inputdata);
})
function sendAjax(url, data){
var data = {'email' : data};
data = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.send(data);
xhr.addEventListener('load', function() {
console.log(xhr.reponseText);
});
}
</script>
</body>
</html>
I expect console shows "{result:ok, email:content in input text "email"}
but the actual output is "undefined".

How to display data from socket io to html page list

So, my program gets data from udp server and i just want to display it in list in HTML page 1 by 1 when it updates.
In console it works, but how to do it on page?
I got this code
index.js
var dgram = require('dgram'),
server = dgram.createSocket('udp4'); //this server gets data from udp packet
var msg;
server.on('message', function (message, rinfo) {
msg = message.toString('ascii'); //udp packet data to string
console.log(msg);
});
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening ' + address.address + ':' + address.port);
});
server.bind(8007);
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
var tm = setInterval(function() {
socket.emit('datafromserver', {'datafromserver': msg});
}, 500);
socket.on('disconnect', function() {
clearInterval(tm);
});
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and html page
<!doctype html>
<html>
<head>
<title>Scoreboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
</style>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io.connect('http://192.168.1.162:3000/');
socket.on('#dataonscreen', function(data) {
$('#dataonscreen').html(data.datafromserver);
console.log(data.datafromserver);
});
</script>
<ul id="dataonscreen"></ul>
</body>
</html>
I can't understand why this isn't working and how to fix it.
Please help!
Your socket.io server emits datafromserver while your code listens for #dataonscreen
Change either so that they are the same value and your code should work. I'm not sure how you have console output since the event is not being listened for

Socket IO randomly send number when idle

i am facing an issue about socket io random send number when idle..
chat.js:
$(document).ready(function(){
var socket = io();
socket.emit("handshaking","");
$('.input').keypress(function (e) {
if (e.which == 13) {
var msg = $('.input').val();
if(msg !=""){
socket.emit("sendMessage",msg);
$('.chat-box').append("<p class='msgSend'>"+msg+"</p><br>");
$('.input').val('');
}
}
});
//If handshaking success, print a message to chat box
socket.on("pong", function(msg){
$('.chat-box').append("<p class='systemMsg'>" + msg + "</p><br>");
});
//Player message
socket.on("getMessage",function(msg){
$('.chat-box').append("<p class='msgReceive'>"+msg+"</p><br>");
});
});
server.js:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var path = require('path');
var mime = require('mime');
var fs = require('fs');
var cache = {};
app.listen(80,function(){
console.log("Listening to port 80.");
});
function send404(res){
res.writeHead(404,{'content-type': 'text/plain'});
res.write('Error 404: resource not found.');
res.end();
}
function sendFile(res, filePath, contents){
res.writeHead(200,{"content-type": mime.getType(path.basename(filePath))});
res.end(contents);
}
function serverStatic(res, cache, path){
if(cache[path]) {
sendFile(res, path, cache[path]);
} else {
fs.exists(path, function(exists) {
if(exists) {
fs.readFile(path, function(err,data) {
if(err) {
send404(res);
} else {
cache[path] = data;
sendFile(res,path,data);
}
});
} else {
send404(res);
}
});
}
}
function handler (req, res) {
var filePath;
if(req.url == '/'){
filePath = 'public/index.html';
console.log(filePath);
} else {
filePath = 'public' + req.url;
console.log(filePath);
}
var path = './' + filePath;
serverStatic(res, cache, path);
}
io.on('connection', function (socket) {
socket.on('disconnect', function(){
console.log('user disconnected');
socket.broadcast.emit("pong","A user has leave the room.");
});
socket.on("handshaking",function(msg){
console.log("A user is joined.");
socket.broadcast.emit("pong", "A user has join the room.");
});
socket.on("sendMessage",function(msg){
socket.broadcast.emit("getMessage",msg);
});
});
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat System</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
<div class="chat-area">
<div class="chat-box"></div>
<input class="input" style="width:100%;" placeholder="Type something"> <!--<button style="">SEND</button>-->
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.slim.js"></script>
<script src="/js/chat.js" type="text/javascript"></script>
</body>
</html>
I am not sure what's wrong with these code but i am sure that all is working except it will auto send some random number when i idle the browser (the page is still on).
Can someone help me take a look on this issue?
Thank you!

Private chat using node.js and socket.io

Im tryng to create a private chat between a key using a node.js and socket.io,
the problem is when i emit a message, that message is not displayed on the room, and i dont know what is the problem...
SERVER
var app = require('express')();
var express = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('./public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
console.log("step 0 OK"); // Works
socket.on('room', function (room) {
console.log("step 1 OK"); // Works
socket.join(room);
});
});
room = "1234";
//THIS CODE NOT WORKING
io.sockets.in(room).emit('message', 'what is going on, party people?');
http.listen(3000, function(){
console.log('listening on *:3000');
});
CLIENT
$(document).ready(function() {
var socket = io('http://localhost:3000');
$("#triggerBtn").on("click", function(e) {
e.preventDefault();
socket.emit('room', '1234');
return false;
});
socket.on('message', function(data) {
console.log("Step 2 OK"); //THIS CODE IS NOT EXECUTED
});
});
HTML
<html>
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<div class="container-fluid">
<li><button type="button" class="btn btn-default" id="triggerBtn">Enviar</button></li>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="./bootstrapPage.js"></script>
</body>
</html>
Sockets can't emit without a connection. move:
io.sockets.in(room).emit('message', 'what is going on, party people?');
inside:
io.sockets.on('connection', function(socket){ ...

Categories

Resources