First of all, I would like to apologize for the horribly worded title; I have been trying to think of one for the past 20 minutes but I do not know a succinct way to describe the problem I am having. If anyone has a better suggestion, please let me know or edit the title if you are able to.
Background: In order to learn NodeJS, I am creating a chat server. When the user clicks the createRoomBtn, an event is created containing the name of the room the user just created, and sent to the socket.js module in app.js, app.js then appends the room to the array of rooms (these rooms are displayed as a list in the browser), and creates a broadcast event to all users including the active user.
Problem: Let's say there is an empty list, and user adds a new room, titled "NodeJS", this will display the room on the screen, and everything is fine and dandy. Now, if I was to add another room, Socket.io, for example, the browser renders the following result: Socket.io, NodeJS, NodeJS. If I was to add "Javascript", the result would be Javascript, Socket.io, NodeJS, Socket.io, Node.JS. Basically, the browser renders the list over and over again, and each time the list shrinks by one. I do not have the slightest idea of why this is happening. The weird thing is that if I press refresh, the browser renders the list correctly Javascript, Socket.io, NodeJS. What is going on?
socket.js:
module.exports = function(io, rooms) {
var chatrooms = io.of('/roomlist').on('connection', function(socket) { //io.of creates a namespace
console.log('Connection established on the server');
socket.emit('roomupdate', JSON.stringify(rooms));
socket.on('newroom', function(data) {
console.log(data);
rooms.push(data);
socket.broadcast.emit('roomupdate', JSON.stringify(rooms));
socket.emit('roomupdate', JSON.stringify(rooms));
})
})
var messages = io.of('/messages').on('connection', function(socket) {
console.log('Connected to the chatroom!');
socket.on('joinroom', function(data) {
socket.username = data.user;
socket.userpic = data.userPic;
socket.join(data.room);
})
socket.on('newMessage', function(data) {
socket.broadcast.to(data.room_number).emit('messagefeed', JSON.stringify(data));
})
})
}
chatrooms.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{title}}</title>
<link rel="stylesheet" href="../css/chatrooms.css">
<script src="//code.jquery.com/jquery-1.11.0.min.js"> </script>
<script src="/socket.io/socket.io.js"> </script>
<script>
$(function() {
var host = '{{config.host}}';
var socket = io.connect(host + '/roomlist');
socket.on('connect', function() {
console.log('connection established');
})
socket.on('roomupdate', function(data) {
$('.roomlist').html('');
var procData = JSON.parse(data);
for (var i = 0; i < procData.length; i++) {
var str = '<a href="room/' + procData[i].room_number + '"><li>'
+ procData[i].room_name + '<li></a>';
$('.roomlist').prepend(str);
console.log(str);
}
})
$(document).on('click', '#createRoomBtn', function() {
var room_name = $('#newRoomText').val();
console.log(room_name);
if (room_name != '') {
var room_number = parseInt(Math.random() * 10000);
socket.emit('newroom', {room_name: room_name, room_number: room_number});
$('#newRoomText').val('');
}
})
})
</script>
</head>
<body>
<div class="cr-userbox">
<img src="{{user.profilePic}}" class="userPic">
<h3 class="username">{{user.fullName}}| Logout</h3>
</div>
<div class="cr-container">
<h1> ChatRooms</h1>
<div class="cr-newroom">
<input type="text" id="newRoomText" autocomplete="off">
<input type="submit" id="createRoomBtn" value=" Create Room">
</div>
<div class="cr-roomlist">
<ul class="roomlist">
</ul>
</div>
</div>
</body>
</html>
Please let me know if more information/modules are required, and I will be happy to provide them.
Update1: As correctly suggested by alex-rokabilis, I have changed $('.roomlist').html() = '' to $('.roomlist').html(''), however, the problem continues to persist.
I'm not sure if this is the cause of your problem or not but you're getting nested list eliments because you have two opening <li> tags in your socket.on ('roomupdate') function
I believe the problem is how you render your rooms in the html part, not how socket.io sends the data.
You use $('.roomlist').html=''; but this is not doing anything! .html is a function in jquery so the right thing to do is $('.roomlist').html('');.
So basically you didn't erase the previous rooms but instead you only add more duplicates. Also something i noticed that is not part of your question, in your nodejs code you use: socket.broadcast.emit('roomupdate', JSON.stringify(rooms));
socket.emit('roomupdate', JSON.stringify(rooms));
if you want to broadcast something to all connected clients there is a function for it and also there is no need to stringify your data, socketio do this internally for you! So you could use something like this:
io.emit('roomupdate',rooms);
Related
Im having a problem with my websocket connection.
(like you probably understand, I want to get a notification when the address gets a transaction, and so on...)
Im not a "superstar" when it comes to javascript, but in my head and from what I read, this should work.
The websocket seem to be open and working, because when I send "op": "blocks_sub" instead of the address, I get the Unconfirmed transactions, and so on...
I would be MORE than grateful if someone could point me in the right direktion of this headache of mine...
Here is my code:
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<title>WebSocket</title>
<h1>WebSocket</h1>
<div id="output" style="font-size: x-large; color: blueviolet;">
output go here ...
</div>
<br>
<script>
$bitcoin_address = "bc1qcg3x50m3785la5qc5tqe2z8htutcn8deyjvc8u";
var btcs = new WebSocket("wss://ws.blockchain.info/inv");
btcs.onopen = function() {
btcs.send(JSON.stringify({
// "op": "blocks_sub"
"op": "addr_sub",
"addr": "$bitcoin_address"
}));
};
btcs.onmessage = function(onmsg) {
var response = JSON.parse(onmsg.data);
var amount = response.x.out[0].value;
var calAmount = amount / 100000000;
document.getElementById("output").innerHTML = calAmount + "btc";
}
</script>
There were no transactions related to this address. Last transaction with the address bc1qcg3x50m3785la5qc5tqe2z8htutcn8deyjvc8u occurred # 2022-01-20 20:09 UTCi.e.~ 11 hours ago.
Probably you subscribed later.
I am trying to use the Have I Been Pwned? API to retrieve a list of breaches for a given email account.
I retrieve this list using the fetch() API. In the browser it looks like there is a connection to the HIBP website but the expected breaches are not visible.
I think this is a JSON problem because the API returns results without a root tree (?) (e.g. [breaches:{"Name"... - only the {"Name"}), so I think I'm making a mistake at the iteration step in the JS file. Also, I'm not calling the 'retrieve' function in the HTML file correctly because the browser throws an error: 'Uncaught ReferenceError: retrieve is not defined', but this is a side-issue (fetch('https://haveibeenpwned.com/api/v2/breachedaccount/test#example.com') doesn't work either).
This is my first week working with JS, fetch(), and JSON, so I consulted a couple of sources before asking this question (but I still can't figure it out, after a couple of days):
How to Use the JavaScript Fetch API to Get Data
fetch API
API methods for HaveIBeenPwnd.com (unofficial)
Where is the actual problem?
The index.html file:
<!DOCTYPE html>
<html lang=en>
<head>
<title>test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
</head>
<body id="top">
<header id="header">
<div class="content">
<h1 style="text-align: center">Put an email in this box</h1>
<input type="email" id="InputBox" value="" autocapitalize="off" spellcheck="false" />
<button type="submit" id="PwnedButton" onclick="retrieve">pwned?</button>
<ul id="results"></ul>
</div>
</header>
<script src="test.js"></script>
</body>
</html>
The test.js file (I know that JS is an interpreted language - so empty characters affect execution speed - but I made it more readable for this example):
function createNode(element) {
return document.createElement(element); // Create the type of element you pass in the parameters
}
function append(parent, el) {
return parent.appendChild(el); // Append the second parameter(element) to the first one
}
const account = document.getElementById('InputBox');
const PwnedButton = document.getElementById('PwnedButton');
const results = document.getElementById('results');
fetch('https://haveibeenpwned.com/api/v2/breachedaccount/' + account)
.then((resp) => resp.json()) // Transform the data into json
.then(function(retrieve) {
let breaches = retrieve.Name; // Get the results
return breaches.map(function(check) { // Map through the results and for each one run the code below
let span = createNode('span'); // Create the element we need (breach title)
span.innerHTML = `${breaches}`;
append(results, span);
})
})
.catch(function(error) {
console.log(JSON.stringify(error));
});
let breaches = retrieve.Name;
retrieve is not an object with a Name property.
It is an array containing multiple objects, each of which has a Name property.
You have to loop over it.
e.g.
retrieve.forEach( item => {
let breaches = retrieve.Name;
console.log(breaches);
});
breaches.map
… and the Name is a string, so you can't map it. You can only map an array (like the one you have in retrieve).
I have created working version of what are you possible going to implement, taking Name field from result. https://jsfiddle.net/vhnzm1fu/1/ Please notice:
return retrieve.forEach(function(check) {
let span = createNode('span');
span.innerHTML = `${check.Name}<br/>`;
append(results, span);
})
function createPost(){
$('#body').append("<p>Welcome to calmspace.</p>");
}
How would I utilize user input so the user can create a post with their own message? I am a newbie with jQuery so if this is a stupid question please forgive me. Possible duplicate but I couldn't find another post like this.
First things first - you should not have added '#' in front of body, it'd mean that the body element is of id 'body', assigning id to an element that is unique does not bear that much sense, instead you should just target the tag - $('body').
In order to provide some sort of message you first have to capture it, for instance using some sort of input. Here is a working demo.
$('#submit').click(function(){
createPost($('#text').val());
})
You read it as follows, grab element of id 'submit', assign it a click event, grab the value of input box of id 'text' and pass it to a function named create post which accepts a string parameter and then prints it in a <p> tag.
#Simion Benderschii a working example of a post which appends to the document or sends via ajax. Hope this helps
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<div>
<h2>Enter your post here</h2>
<form>
<textarea id='user-input-post'></textarea>
<div>
<button id=user-post-button>Post</button>
</div>
</form>
</div>
<div>
<h2>Below are your posts</h2>
<ul id='user-post-display'>
</ul>
</div>
</body>
<script>
/*possible options can be
'display' - which shows the post in the UI in a unordered list
'ajax' - which send the post to the server via ajax
*/
var post_type = 'display';
//the id of the list where the post will be appended
var list_id = '#user-post-display';
//the id where the post will be entered
var post_id = '#user-input-post';
//the id of the button which triggers some action
var button_id = '#user-post-button';
//this gets the post from the textarea
var get_post = function() {
var post = $(post_id).val();
return encodeURIComponent(post);
};
//this appends the post to the list
var append_post = function() {
var post = get_post();
var html_string = '';
if (post) {
html_string = '<li>' + post + '</li>';
$(list_id).append(html_string);
}
};
//this sends the post via ajax and triggers callbacks
var send_post = function() {
var post = get_post();
var post_created_on = Date.now();
var url = 'dummy_url_for_posting';
$.ajax({
method: 'POST',
url: url,
data: { data: {
post: post,
post_created_on: post_created_on
}}
})
.done(function() {
window.alert('post success');
})
.fail(function() {
window.alert('post fail');
})
.always(function() {
window.alert('post triggered');
});
}
//main function which is the entry point
var main = function() {
$(button_id).on('click', function() {
event.preventDefault();
debugger;
if (post_type === 'display') {
append_post();
} else if (post_type === 'ajax') {
send_post();
}
});
};
//triggers the main function
main();
</script>
</html>
I am not exactly sure what you want to do from your question. In future questions you will find it helpful to provide more detail on exactly what you want to do with your application or function.
The basic idea here is to use a button or any action you can capture with jQuery (like pressing enter or checking $(element).on('click',... and then putting that info where you want using $(element).html(...) or .append(...).
Here is a fiddle I made with the rough idea. Try to use this fiddle tool a lot, and you can also post the link to what you have tried in future questions. Good luck :-)
JSFiddle example of submitting a post
Right now we have a web application that is ran on a local network where the clients run everything in javascript. In order to make sure everything is in sync these clients currently utilize an AJAX request to the server by sending the last "syncId" that it has recieved. The server then responds with an array tree of commands to get this client up to date. This is executed every second and has yet to cause any issues with network bandwith or latency however we are installing a system in a bigger client next month that may push the limits of this method and I am wondering if it is feasible to have the server "PUSH" the sync events to the clients in real time.
srvResponse=httpGet("CDSSync.php?sessionKey="+sessionKey+"&lastUpdate="+lastUpdate);
if(srvResponse!=0){
syncEvents=srvResponse.split(";");
for(var i=0; i<syncEvents.length; i++){
syncItem=syncEvents[i].split(",");
window["syncFunction_"+syncItem[1]](syncItem[2]);
lastUpdate=syncItem[0];
}
}
The above is where my system checks for events to be synced where syncItem[0] is a autoIncrement ID, syncItem[1] is a code for the event being handled and syncItem[2] is a parameter for the function. the httpGet function being called although not in this code is just a function that fetches from the server and returns the response.
Take a look at www.firebase.com, you can set up a push service from javascript clients to all others in minutes. Try the simple tutorial first:
<!doctype html>
<html>
<head>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
</head>
<body>
<div id='messagesDiv'></div>
<input type='text' id='nameInput' placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message'>
<script>
var myDataRef = new Firebase('https://hbw30ob2a8y.firebaseio-demo.com/');
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
myDataRef.push({name: name, text: text});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
</body>
</html>
I am using tokbox trial for video chatting on my website. But the problem i am facing is that ::: User 1 can see and hear User 2 clearly. User 2 can see User 1 clearly, but user 2 couldnt here user 1. And code i am using
<html>
<head>
<title>Monkvyasa | Test</title>
<script src='http://static.opentok.com/webrtc/v2.2/js/opentok.min.js'></script>
<script type="text/javascript">
// Initialize API key, session, and token...
// Think of a session as a room, and a token as the key to get in to the room
// Sessions and tokens are generated on your server and passed down to the client
var apiKey = "xxxxxxx";
var API_KEY=apiKey;
var sessionId = "2_MX40NTAyMDgxMn5-xxxxxxxxxxxxxxxxxxxxHBXZEZoWHN-fg";
var token = "T1==cGFydG5lcl9pZD00NTAyMDgxMiZzaWc9ZDNiYjYyZGE2NTBkYmUzMTUyNGNjNDZjYzAzY2NjZWRhZGY3NTEyZjpyb2xlPW1vZGVyYXRvciZzZXNzaW9uX2lkPTJfTVg0xxxxxxxxxxxxxxxxxxxxxxxxBNM1JsYlRCUFdXWkhSSEJYWkVab1dITi1mZyZjcmVhdGVfdGltZT0xNDEzMjAwMjIxJm5vbmNlPTAuMTk1MzEwNTU0MzY1MjEwNSZleHBpcmVfdGltZT0xNDEzMjg0MzY5";
// Initialize session, set up event listeners, and connect
var session;
var connectionCount = 0;
function connect() {
session = TB.initSession(sessionId);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.addEventListener('streamCreated', function(event){
e=event;
console.log(e);
for (var i = 0; i < event.streams.length; i++) {
streams = event.streams;
// Make sure we don't subscribe to ourself
alert("new user connected :)");
if (streams[i].connection.connectionId == session.connection.connectionId) {
return;
}
// Create the div to put the subscriber element in to
var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);
document.body.appendChild(div);
session.subscribe(streams[i], div.id);
}
});
session.connect(API_KEY, token);
}
function sessionConnectHandler(event) {
var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
// This example assumes that a publisherContainer div exists
publisherContainer.appendChild(div);
var publisherProperties = {width: 500, height:450};
publisher = TB.initPublisher(API_KEY, 'publisher', publisherProperties);
session.publish(publisher);
}
function disconnect() {
session.disconnect();
}
connect();
</script>
</head>
<body>
<h1>Monkvysa videofeed test!</h1>
<input style="display:block" type="button" id="disconnectBtn" value="Disconnect" onClick="disconnect()">
<table>
<tr>
<td> <div id="publisherContainer"></div></td> <td><div id="myPublisherDiv"></div></td>
</tr>
</table>
</body>
</html>
Thanks in advance
The code looks mostly correct, except you're using an older form of the 'streamCreated' event handler. In the latest version of the API, you no longer need to iterate through the event.streams array, you actually get one invocation of the event handler per stream.
In order to further dig into the problem, would you be able to add a link to a gist containing all the console logs? To make sure the logs are being outputted, you can call OT.setLogLevel(OT.DEBUG); at the beginning of the script.
Lastly, the newer API is greatly simplified and you could save yourself the effort of DOM element creation and iteration. What you have implemented is basically identical to our Hello World sample applications, which you can find in any of our server SDKs, for example here: https://github.com/opentok/opentok-node/blob/61fb4db35334cd30248362e9b10c0bbf5476c802/sample/HelloWorld/public/js/helloworld.js