Get socket.id when page reload node Js and Socket.io - node.js

near time . I try write chat app using node Js and Socket.io , i have 1 page login.html , 1 page chat.html and server.js file . When i login with UserA, i will send email and pass to server and verify it . After , go to page chat.html . Here , i show list user , but when i try refresh page chat.html , socket.id changed . I have solution save socket.id after refresh in database MongoDb , but when i log in with UserB other browser , and after refresh page of UserA , but socket.id of UserB changed , not User A . Sorry for my English.
This is login.html page
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<div class="container">
<form class="form-signin" id="formLogin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
jQuery(function ($){
var socket= io.connect('http://localhost:8080');
var $email =$('#inputEmail'),
$password=$('#inputPassword'),
$login=$('#formLogin');
$login.submit(function (event){
socket.emit('login', { email:$email.val(), password:$password.val()});
socket.on('CheckLogin', function (data){
console.log('show something');
if(data){
console.log(data);
window.location.href='chat';
}else {
alert('Tai khoan hoac mat khau khong dung');
}
});
/* ,function (data){
console.log(data);
if(data){
console.log('Login successfuly');
window.location.href = "chat";
socket.on('sendId', function(data){
console.log(data[0]._id);
});
}else {
console.log('Login faile');
}
}*/
event.preventDefault();
});
});
</script>
</body>
</html>
This is server.js file
var app = require('express')(),
server = require('http').Server(app),
io=require('socket.io')(server),
mongoose=require('mongoose');
server.listen(8080);
var mongoURL = 'mongodb://localhost/ChatDatabase';
app.get('/login', function(req, res){
res.sendFile(__dirname+'/signin.html');
});
var emailprecentLogin='';
var namePreLogin = '';
var logInStatus = false;
var Users= mongoose.model('Users',{
email :String,
name:String,
password:String,
socketId :String
});
var Messages = mongoose.model('Messages',{
name :String,
message:String
});
/*list variable*/
var mailLogin = '';
var statusLogin = false ;
var listLogin =[];
mongoose.connect(mongoURL , function(err, db){
if(err){
console.log('Connect err');
}else {
console.log('Connect successfuly');
/*get value send from loginform and verify*/
io.on('connection', function (socket){
socket.on('login', function (data){
var tmpEmail = data.email ;
var tmpPass= data.password ;
mailLogin = data.email;
console.log('info login' + tmpEmail + tmpPass);
Users.findOne({ email:tmpEmail, password:tmpPass }).exec(function(err , docs){
if(docs==null){
console.log(err +typeof(docs));
socket.emit('CheckLogin', false);
}else {
if(docs.email == tmpEmail && docs.password==tmpPass){
statusLogin=true;
socket.emit('CheckLogin', true);
console.log('Info of user login:'+docs + typeof(docs));
app.get('/chat', function (req, res){
res.sendFile(__dirname+'/chat.html');
});
}
}
});
});/*end verify login*/
socket.emit('tmpEmailLogin',mailLogin );
/*update socket id when user f5 or refresh page*/
socket.on('connectServer', function(data){
/*console.log(data);*/
console.log('User F5'+data);
var tmpSocketId = socket.id ;
var tmpLogin = data;
Users.update({email:data},{$set:{socketId:tmpSocketId}},function (err, userUpdate){
if(err){
/*console.log(err);*/
console.log("err sendSocketID");
}else {
Users.find({}).exec(function(err, docs){
if(err){
console.log('Err find list user');
}else {
socket.emit('listUser', docs);
}
});
Users.find({email:mailLogin}).exec(function(err, docs){
if(err){
console.log('Err find list user');
}else {
console.log('Updated socketId');
/*console.log(docs);*/
}
});
}
});
});
/*update socket when user click item*/
socket.on('updateSocketId', function(data){
Console.log('user f5 :' + mailLogin);
});
});
}
});
This is chat.html file
<!DOCTYPE html>
<!-- saved from url=(0040)http://getbootstrap.com/examples/signin/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://getbootstrap.com/favicon.ico">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" >
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Chat</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<style type="text/css">
#viewContent{
color: black ;
height: 400px;
background-color: #F5F5F5;
overflow: scroll;
}
#listUser{
height: 400px;
}
</style>
</head>
<body>
<div id='header'>
<h2 class="title">This is chat box</h2>
</div>
<div id='content' >
<div id='listUser' class='col-md-4'>
<li id ='list' class = "list-group-item active">List User</li>
</div>
<div name='chatbox' class='col-md-8'>
<li id ='yourname' class = "list-group-item active">Your Name</li>
<div id='viewContent'></div>
<div name='formInput' >
<form class='' id='formChat'>
<div class="form-group">
<label class="sr-only" for="contentChat">Enter message</label>
<input type="text" class="form-control" id="contentChat" placeholder="Enter message" />
<input type='submit' class='btn btn-primary ' value ='Send'/>
</div>
</form>
</div>
</div> <!-- chat box div -->
</div>
<script type="text/javascript">
jQuery(function($){
var socket = io.connect('http://localhost:8080');
var $contentChat = $('#contentChat'),
$send =$('formChat');
var tmpEmailLogin;
var listID = [];
var idSocket='' ;
var emailPre= '';/*user login precent*/
var tenLogin ='';
var value_id ='';
/*<----------- chat
send list user form server
set connect 2 user
show message
------------->*/
/* socket.on('infoLogin', function(docs){
emailPre=docs ;
});*/
/*send list user */
socket.on('tmpEmailLogin', function(data){
tmpEmailLogin = data;
/*console.log(data);*/
socket.emit('connectServer',tmpEmailLogin); /*gửi socket để set socketId lên database*/
});
/*console.log('user login :' +tmpEmailLogin);*/
socket.on('listUser', function(data){/* show list user in database*/
console.log('socketId listUser :' + socket.id);
var j = 0 ;
/*console.log('Email login:' +emailPre);*/
$('#listUser').empty();
for(var i =0 ; i<data.length; i++){
$('#listUser').append('' +data[i].name+ '');
}
});
var click = 0 ;
$(document).on('click', 'a.list-group-item', function(event){
click ++;
$('#viewContent').innerHTML='';
if(click =1){
$('a.list-group-item').each(function(i , obj){
this.setAttribute("class", " list-group-item");
click = 0 ;
$('#viewContent').empty();
});
}
/*emailLogin=this.id;*/
var reqIdOfEmail = this.id;
this.setAttribute("class", " list-group-item active");
socket.emit('updateSocketId', reqIdOfEmail);
socket.on('ResSocket', function (data){
idSocket = data.idSk;
nameOfSk = data.nameReq ;
console.log(nameOfSk+idSocket );
});
event.preventDefault();
}); /* end click*/
$('#formChat').submit(function(event){
var $contentMsg = $('#contentChat').val();
/*alert($contentMsg);*/
if(idSocket!=''&& idSocket!=null){
socket.emit('SendMsg', {idsocket:idSocket, msg:$contentMsg, name:tenLogin})
}
event.preventDefault();
});
/*P2P message*/
socket.on('P2Pmessage', function (data){
/*var nameReq= data.name;*/
console.log('show something here');
var msgContent=data.content;
$('#viewContent').append('<b></b>'+msgContent +'<br>' );
});
});
</script>
</body>
</html>

You can join your users to same room,
So even if socketId will change
they can send and receive messages.
In connection you join room with this code:
io.on('connection', function(socket){
socket.join('some room');
});
And send message to room:
io.to('some room').emit('some event'):
You can find more documentation here.

Related

Use a Checkbox to Show Disabled Users

I'm making a website in which I show enabled users in a Bootstrap by default, but there's a checkbox to show all users. But I'm not sure how I can go about implementing it properly.
I thought about doing:
<form class="" action="/admin" method="get">
<input type="checkbox" name="showDisabled" value="">
<input type="submit" name="" value="">
</form>
And in my /admin route:
if (req.body.showDisabled) {
User.find({}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.render('pages/userTable', {users: users});
})
} else if (!req.body.showDisabled) {
User.find({enabled: true}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.render('pages/userTable', {users: users});
})
}
But that seems really janky. What's a better way to do it?
You can try this:
Router
app.get('/getDiasbleUser', function(req, res) {
var getDiasbleUser = req.params.showDisabled
if (getDiasbleUser == "Yes") {
User.find({}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.send(users);
})
} else if (getDiasbleUser == "No") {
User.find({
enabled: true
}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.send(users);
})
}
})
HTML (Template)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</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.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form class="" action="/admin" method="get">
<input type="checkbox" id="disableId" name="showDisabled" value=""><br>
<div id="appendValue"></div>
<br>
<button class="btn btn-primary">Submit</button>
</form>
</div>
</body>
//Ajax call
<script>
$('#disableId').on('click', function () {
$(this).val(this.checked ? 1 : 0);
//console.log($(this).val());
var url = "";
if($(this).val() == 1){
url = "/getDiasbleUser?showDisabled=yes"
} else {
url = "/getDiasbleUser?showDisabled=no"
}
$.ajax({
url: url,
success: function(data){
//Here data will be return result(You will append into div or table)
//like : $('#appendValue').append(data)
}
})
});
</script>
</html>

Socket.io opening hundreds of connections

This is my server.js code:
var express =require('express'),
http = require('http');
var app= express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.Port || 3000);
console.log('server running ...')
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
socket.on('disconnect',function(data){
users.splice(users.indexOf(socket.username),1);
updateUsernames();
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets conected', connections.length);
});
//send message
socket.on('send message', function(data){
console.log(data)
io.sockets.emit('new message',{msg: data, user: socket.username});
});
//new User
socket.on('new user', function(data,callback){
callback(true);
socket.username = data;
users.push(socket.username);
updateUsernames();
});
function updateUsernames(){
io.sockets.emit('get users', users)
}
});
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<title>IO chat</title>
<link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<style >
body{
margin-top: 30px;
}
#messageArea{
display: none;
}
</style>
</head>
<body>
<div class = "container">
<div id = "userFormArea" class= "row">
<div class = "col-md-12">
<form id = "userForm">
<div class = "form-group">
<label>Enter Username</label>
<input class = "form-control" id = "username">
<br/>
<input type="submit" class = "btn btn-primary" value = " Login"/>
</div>
</form>
</div>
</div>
<div class = "row" id = "messageArea">
<div class = "col-md-4">
<div class = "well">
<h3> Online users </h3>
<ul class = "list-group" id = "users"> </ul>
</div>
</div>
<div class = "col-md-8">
<div class="chat" id = "chat"> </div>
<form id = "messageForm">
<div class = "form-group">
<label>Enter Message</label>
<textarea class = "form-control" id = "message"> </textarea>
<br/>
<input type="submit" class = "btn btn-primary" value = "Send Message"/>
</div>
</form>
</div>
</div>
</div>
<script>
$(function(){
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $userFormArea = $('#userFormArea');
var $userForm = $('#userForm');
var $messageArea = $('#messageArea');
var $users = $('#users');
var $username = $('#username');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data){
$chat.append('<div class = "well"><strong>'+data.user+'</strong>:' + data.msg + '<div>');
});
$userForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $username.val(),function(data){
if(data){
$userFormArea.hide();
$messageArea.show();
}
});
$username.val('');
});
socket.on('get users', function(data){
var html = '';
for (i = 0; i< data.length; i++){
html +='<li class = "list-group-item" >' + data[i]+ '</li>';
}
$users.html(html);
});
});
</script>
</body>
</html>
I've been struggling for this for a while, is it something wrong with socket.io? Or is it something that I am doing wrong.
If there's something different I have to do, please let me know. I literally connect to the socket, and it spews out console logs.
As you can see in the picture, I want it to say Connected: 1 sockets connected after ONE person connections.
This usually occurs when client and server are using different versions of socket.io. Check the version of server from package.json and give client the same version. I had the same issue and upgrading to socket.io version 2.1.1 fixed it.

How to create html table dynamically from database with node.js and express?

I am totally new in node.js and I want to create a simple phonebook app with express and postgresql. I want to have two pages, one to add a new contact and another one for contacts to be shown in an html table with the ability to update or delete rows. Until now I have implemented the insert but I don't know how to create the "contacts.html" page dynamically from database. Thank you in advance!
index.html
<header>
<ul>
<li><h2>Phonebook</h2></li>
<li>New Contact</li>
<li>Contacts</li>
</ul>
</header>
<section>
<form action="insertContact">
<p>Full Name</p>
<input type="text" name="fullname" required>
<p>Phone</p>
<input type="text" name="phone1" required>
<p>Mobile</p>
<input type="text" name="phone2">
<p>Address</p>
<input type="text" name="address" required> <br><br>
<input type="submit" name="submitBtn" id="submitBtn" value="Submit">
</form>
</section>
server.js
var express = require('express');
var path = require('path');
var db = require('pg');
var http = require('http');
var app = express();
app.use(express.static(path.join(__dirname,'/')));
var dbConnection = "postgres://postgres:root#localhost:5432/Phonebook";
app.get('/insertContact',function(req,res){
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "insert into Contacts (fullname,phone,mobile,address) values ($1,$2,$3,$4)";
var fullname = req.query.fullname;
var phone = req.query.phone1;
var mobile = req.query.phone2;
var address = req.query.address;
var contact = [fullname , phone , mobile , address];
dbClient.query(query , contact , function(err){
if(err)
throw err;
else {
console.log('Success!') ;
res.redirect('/');
res.end();
}
});
});
});
app.get('????',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts";
dbClient.query(query,function(err,result){
if(err)
throw err;
else {
??????????
res.end();
}
});
});
});
app.listen(8080,function(){
console.log('Server started');
});
sample image
You can do that by using any javascript template language one of the most popular is EJS "embedded javascript" its very easy to integrate and use with node js
You simply create your template and pass any variable like an array.
Check the code below this is how you add a template in EJS
<html >
<head>
<meta charset="utf-8">
</head>
<body>
<section class="home">
<h1>Contacts list</h1>
<ul class="list-group">
<% for(var i=0; i<contacts.length; i++) {%>
<li class="list-group-item">
<span>Name: </span><%= contacts[i].name %>
<br/>
<span>Phone: </span><%= contacts[i].phone %>
</li>
<% } %>
</ul>
</section>
</body>
</html>
Then in your node js route handler will just render that template and pass the required data.
app.get('????',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts";
dbClient.query(query,function(err,result){
if(err)
throw err;
else {
res.render('contacts.ejs', { contacts: result });
}
});
});
});
One final step is to tell node that it will use ejs as template language.
app.set('view engine', 'ejs');
And don't forget to npm install --save ejs
Thanks to Amr Labib's help
server.js
var express = require('express');
var path = require('path');
var db = require('pg');
var app = express();
app.use(express.static(path.join(__dirname,'/')));
app.set('view engine', 'ejs');
var dbConnection = "postgres://postgres:root#localhost:5432/Phonebook";
// Insert Contact
app.get('/insertContact',function(req,res){
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "insert into Contacts (fullname,phone,mobile,address) values ($1,$2,$3,$4)";
var fullname = req.query.fullname;
var phone = req.query.phone;
var mobile = req.query.mobile;
var address = req.query.address;
var contact = [fullname , phone , mobile , address];
dbClient.query(query , contact , function(err){
if(err)
throw err;
else {
console.log('Contact Inserted!') ;
res.redirect('/');
res.end();
}
});
});
});
// Form Handling - Update Row / Delete Row
app.get('/handleForm',function(req,res){
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
if(req.query.deleteBtn != null){
var query = "delete from Contacts where id = ($1)";
var id = [req.query.id];
dbClient.query(query , id , function(err){
if(err)
throw err;
else {
console.log('Contact Deleted!') ;
res.redirect('/contacts.html');
res.end();
}
});
} else if(req.query.updateBtn != null) {
var query = "update Contacts set fullname=($1),phone=($2),mobile=($3),address=($4) where phone=($5)";
var fullname = req.query.fullname;
var phone = req.query.phone;
var phoneHidden = req.query.phoneHidden;
var mobile = req.query.mobile;
var address = req.query.address;
dbClient.query(query , [fullname,phone,mobile,address,phoneHidden], function(err){
if(err)
throw err;
else {
console.log('Contact Updated!') ;
res.redirect('/contacts.html');
res.end();
}
});
}
});
});
// Search contact by phone
app.get('/searchContact',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts where phone=($1)";
var searchBoxValue = req.query.searchBoxValue;
dbClient.query(query , [searchBoxValue], function(err,result){
if(err)
throw err;
else {
res.render('searchedContact.ejs' , {contacts: result});
res.end();
}
});
});
});
// Show Contact's Table
app.get('/contacts.html',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts";
dbClient.query(query,function(err,result){
if(err)
throw err;
else {
res.render('contacts.ejs', { contacts: result });
res.end();
}
});
});
});
app.listen(8080,function(){
console.log('Server started');
});
contacts.ejs
<section id="table">
<div class="table">
<div id="headers">
<span id="id">id</span>
<span id="fullname">Name</span>
<span id="phone">Phone</span>
<span id="mobile">Mobile</span>
<span id="address">Address</span>
</div>
<% for(var i = 0; i < contacts.rows.length; i++) { %>
<form class="tr" action="handleForm">
<input type="text" id="id" name="id" class="td" readonly value= <%= contacts.rows[i].id %>>
<input type="text" name="fullname" class="td" value= <%= contacts.rows[i].fullname %>>
<input type="text" name="phone" class="td" value= <%= contacts.rows[i].phone %>>
<input type="text" name="mobile" class="td" value= <%= contacts.rows[i].mobile %>>
<input type="text" name="address" class="td" value= <%= contacts.rows[i].address %>>
<input type="submit" name="updateBtn" id="updateBtn" value="update" class="td">
<input type="submit" name="deleteBtn" id="deleteBtn" value="delete" class="td">
<input type="hidden" name="phoneHidden" id="phoneHidden" class="td" value=<%= contacts.rows[i].phone %> >
</form>
<% } %>
</div>
</section>

In response.write() TypeError: First argument must be string or Buffer

I have created a server in Node and I am calling fb.html through it. Now when I visit http://localhost:8081/ I keep on getting the following error:
http://oi67.tinypic.com/rkde9d.jpg
// server.js
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
fs.readFile("fb.html","utf8", function(err, data){
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
response.end();
});
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
// fb.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<script>
var acces_token, object_id=null,id;
// initialize and setup facebook js sdk
window.fbAsyncInit = function() {
FB.init({
appId : 'myappID',
xfbml : true,
version : 'v2.6'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// function to login to facebook
function myFBLogin() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("You are already logged in!");
}
else{
FB.login(function(response){
// user is now logged in
console.log(response);
acces_token=response.authResponse.accessToken;
}, {scope: 'publish_actions' , scope:'user_posts' });
}
});
}
// function to logout
function myFBLogout(){
FB.getLoginStatus(function(response) {
if (response.status === 'unknown') {
alert("You are already logged out!");
}
else{
console.log(response);
FB.logout(function(response) {
// user is now logged out
alert("You are successfully Logged Out!");
acces_token=null;
if(object_id==null)
document.getElementById('status').innerHTML="Post ID is unknown";
else
document.getElementById('status').innerHTML="You are logged out";
});
}
});
}
// function to post an image on wall
function myFacebookPost()
{
FB.api("/me/photos",
'post',
{url: document.getElementById("frm1").elements[0].value},
function (response){
console.log(response);
if(response.error){
if(response.error.code==2500)
{
alert("You are not logged in!");
}
else if(response.error.code==1)
{
alert("Image url is not correct!");
}
else if(document.getElementById("frm1").elements[0].value=="") alert("Enter the URL!");
}
else{
id=response.post_id;
object_id=response.id;
document.getElementById('status').innerHTML=0;
}
}
);
}
//function to count number of likes
function like_count(){
var a=FB.getAuthResponse();
FB.api(
"/"+object_id+"/likes",
'get',
function (response) {
console.log(response);
if(response.error){
if(object_id==null)
{
alert("Object ID is not defined. First create a post!");
}
else if(response.error)
{
alert("You are not logged in!");
}
}
else
document.getElementById('status').innerHTML=response.data.length;
}
);
}
</script>
<button onclick="myFBLogin()">Login to Facebook</button>
<button onclick="myFBLogout()">Logout</button><br><br>
<form id="frm1" action="javascript:myFacebookPost()">
Image URL: <input type="text" name="URL" placeholder="Enter the image url" >
<input type="submit" value="Post Image on Wall" style="display: inline">
</form>
<br>
<button onclick="like_count()" >Likes count</button>
<p style="display: inline">   Likes Count =  </p>
<div id="status" style="display: inline"> Post ID is unknown</div>
</body>
</html>
Please help to find the problem. Well I have that if works fine on systems while on others it raises the above error.

socket.io nodeJs angularjs one to one chat

I'm new to NodeJs. Now I'm trying socket.io. I want to build website like Zopim(https://www.zopim.com/). Now I'm struggling with : client(A) should get helpline from one admin only and to prevent other admins to chat with client(A).
This is server.js
var app = require('express')();
var bodyParser = require('body-parser');
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(require("express").static('data'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
/* Creating MySQL connection.*/
var con = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database :'Chat_tryout'
});
var insertRecord = 'Insert into mytable(socketid,receiver,message)value(?,?,?)';
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
});
var msg={};
io.on('connection', function(socket){
console.log(socket.id + "connected");
socket.on('message',function(msg){
console.log('user' +this.id+ 'sent message"'+ msg +'"');
//console.log(" admin id " + io.sockets.connected[socketid]);
con.getConnection(function(err, connection) {
var message=msg;
var socketid=" ";
con.query( insertRecord,[socketid,socket.id,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ("inserted"+ socket.id +"message"+ msg);
//res.end(``);
});
});
app.post('/get_data', function (req, res) {
var msg=req.body.name;
var toid = req.body.toid;
//var socketid = this.socket.sessionid;
//console.log(socketid);
console.log(toid);
io.to(toid).emit('mymessage',msg);
con.getConnection(function(err,connection){
var message=msg;
con.query( insertRecord,[socketid,toid,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ( "inserted "+ socket.id +" message "+ msg);
});
});
});
});
socket.on('disconnect', function() {
console.log('client socketio disconnect!');
});
app.get('/api/getalldata', function(req,res){
con.getConnection(function(err,connection){
con.query( 'select * from mytable', function(err, rows) {
if(err){
console.log("error:" + err);
}else
console.log ("success");
res.json(rows);
});
});
});
});
http.listen(8080,function(){
console.log("Listening on http://127.0.0.1:8080/");
});
Index.html :
(ADMIN PAGE)
<html ng-app="sample">
<head>
<title>Connecting Node.js app to MySql</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script type="text/javascript">
var app = angular.module('sample',[]);
app.controller('sample', function ($scope,$http,$timeout) {
$scope.data_server={};
$scope.socketid={};
var TypeTimer;
var TypingInterval = 1000;
$scope.keyup = function() {
$timeout.cancel(TypeTimer);
TypeTimer=$timeout( function(){ get_data(); }, TypingInterval);
};
$scope.keydown = function(){
$timeout.cancel(TypeTimer);
};
function get_data(){
var name=$scope.name;
var toid = $scope.toid;
$http.post('/get_data',{name:name,toid:toid}).success(function(data, status, headers, config) {
// $scope.data_server=data;
}).error(function(data, status) {
//alert("Connection Error");
});
}
$scope.getalldata = function(){
$http.get('/api/getalldata')
.success(function(data) {
$scope.data_server = data;
// console.log(data);
})
.error(function(err) {
console.log('Error: ' + err);
});
};
});
</script>
</head>
<body ng-controller="sample">
<div class="container">
<div id="name-group" class="form-group">
<h2>ADMIN</h2>
<ul id="messages"></ul>
<br/>
<input type="text" class="form-control" ng-model="name" placeholder="Type here and check the Title in Tab"/>
<input type="text" class="form-control" ng-model="toid" ng-keyup="keyup()" ng-keydown="keydown()" ng-blur="blur()" ng-change="change()"/>
{{toid}}
<br/>
</div>
<div class="table-responsive">
<table class="table table-hover"ng-repeat="data in data_server" >
<thead>
<tr>
<th>From</th>
<th>Message</th>
</thead>
<tbody>
<tr>
<td>{{data.receiver}}</td>
<td>{{data.message}}</td>
<!-- <td><input type="text" value="{{data.receiver}}"><td>
<td><input type="text" ng-model="reply" ng-keyup="submit()"></td>-->
</tr>
</tbody>
</table>
</div>
<div class="rows">
<div class="col-md-12">
<div class="data" >
<!---{{ data_server}}--->
<hr/>
</div>
<div ng-show="data_server.length == 0" >
<div class="alert alert-info" >
<p class="text-center" >
Sorry, Right now we don't have any results for you.
</p >
</div >
</div >
</div>
</div>
<div class="rows">
<button class="btn btn primary" ng-click="getalldata()">Get Messages</button>
<div class="form-row form-last-row">
</div>
</div>
</div>
</body>
<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>
<script>
var socket = io.connect("http://localhost:8080");
socket.on('message', function(msg){
$('#messages').append($('<li>').text(msg));
});
I'm having html front end for client where they emit and receive messages using:
var socket = io.connect("http://localhost:8080");
$('form').submit(function(){
socket.emit('message', $('#message').val());
$('#message').val('');
return false;
});
socket.on('mymessage', function(msg){
$('#messages').append($('<li>').text(msg));
});

Resources