Only Show Messages with RoomID in Firebase - javascript

I am trying to create FireBase chat with separate rooms and only display messages from that room. How can I only show messages with roomid = somenumber (currently set to 4)
Data might look like this:
This is the code following the firebase documentation.
<body>
<!-- CHAT MARKUP -->
<div class="example-chat l-demo-container">
<header>Firebase Chat Demo</header>
<div class='example-chat-toolbar'>
<label for="nameInput">Username:</label>
<input type='text' id='nameInput' placeholder='enter a username...'>
</div>
<ul id='example-messages' class="example-chat-messages"></ul>
<footer>
<input type='text' id='messageInput' placeholder='Type a message...'>
</footer>
</div>
<!-- CHAT JAVACRIPT -->
<script>
// CREATE A REFERENCE TO FIREBASE
var messagesRef = new Firebase('https://blistering-fire-1740.firebaseio.com/');
// REGISTER DOM ELEMENTS
var messageField = $('#messageInput');
var nameField = $('#nameInput');
var messageList = $('#example-messages');
// LISTEN FOR KEYPRESS EVENT
messageField.keypress(function (e) {
if (e.keyCode == 13) {
//FIELD VALUES
var username = nameField.val();
var message = messageField.val();
//SAVE DATA TO FIREBASE AND EMPTY FIELD
messagesRef.push({name:username, text:message, roomid:4});
messageField.val('');
}
});
// Add a callback that is triggered for each chat message.
messagesRef.limitToLast(10).on('child_added', function (snapshot) {
//GET DATA
var data = snapshot.val();
var username = data.name || "anonymous";
var message = data.text;
//CREATE ELEMENTS MESSAGE & SANITIZE TEXT
var messageElement = $("<li>");
var nameElement = $("<strong class='example-chat-username'></strong>")
nameElement.text(username);
messageElement.text(message).prepend(nameElement);
//ADD MESSAGE
messageList.append(messageElement)
//SCROLL TO BOTTOM OF MESSAGE LIST
messageList[0].scrollTop = messageList[0].scrollHeight;
});
</script>
</body>
firebase doc

Dan's answer will work, but it means that you're downloading all the chat messages. User's on smaller data plans will appreciate it if you don't download data that is not needed:
var roomMessages = messagesRef.orderByChild('roomid').equalTo(4);
roomMessages.limitToLast(10).on('child_added', function (snapshot) {
//GET DATA
var data = snapshot.val();
You'll need an index on roomid, as described here.

Simply filter out messages that don't belong to that room, when you add them to the DOM.
// Add a callback that is triggered for each chat message.
messagesRef.limitToLast(10).on('child_added', function (snapshot) {
var data = snapshot.val();
// break out of the function early if this message does not
// belong in this room.
if(data.roomId !== 4) return;
var username = data.name || "anonymous";
var message = data.text;
// ...
});
You probably don't want to hardcode the roomID into your code. It would make sense to store the current room ID in a variable somewhere, then check against that instead.
var currentRoomId = getRoomId(); // get from URL, or from Firebase
// ...
if(data.roomId !== currentRoomId) return;

Related

onload Function and Document Ready function in JS creating conflict

So I'm working on a section of my Website which has a TODO List built in not I want the data to load just like other data that are loading alongside the page. I tried having onload in Body Tag in my HTML and I had also tried to $(document).ready(function(){}) as well however neither of them seemed to work nor was I getting any errors in my console. But the function is working as it is also link to another function which runs on click of a button which I don't want to keep happening. I want it to be seamless. Is there any reason why this might not be working.
Thanks for any help in advance.
My HTML and Javascript Code:
function create() {
unfinished_task_container = document.getElementById("main_container");
unfinished_task_container.innerHTML = "";
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
task_array = [];
firebase
.database()
.ref("/Users/" + uid + "/todo/")
.once("value", (snapshot) => {
snapshot.forEach((childSnapshot) => {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
task_array.push(Object.values(childData));
});
for (var i = 0; i < task_array.length; i++) {
task_key = task_array[i][0];
task_title = task_array[i][1];
//Data
task_container = document.createElement("div");
task_container.setAttribute("class", "task_container");
task_container.setAttribute("data-key", task_key);
task_data = document.createElement("div");
task_data.setAttribute("id", "task_data");
title = document.createElement("p");
title.setAttribute("id", "task_title");
title.setAttribute("contenteditable", false);
title.innerHTML = task_title;
//Tools
task_tool = document.createElement("div");
task_tool.setAttribute("id", "task_tool");
task_done_button = document.createElement("button");
task_done_button.setAttribute("id", "task_done_button");
task_done_button.setAttribute(
"onclick",
"task_done(this.parentElement.parentElement, this.parentElement)"
);
task_done_button.setAttribute("onclick", "task_done()");
fa_done = document.createElement("i");
fa_done.setAttribute("class", "fa fa-check");
unfinished_task_container.append(task_container);
task_container.append(task_data);
task_data.append(title);
task_container.append(task_tool);
task_tool.append(task_done_button);
task_done_button.append(fa_done);
}
});
}
<body onload="create();">
<div class="dentistToDo">
<p class="divlable">Your Personal To Do List</p>
<input id="input_box" placeholder="What needs to be done?" />
<button id="input_button" onclick="add_task()">Add Task</button>
<div class="container" id="main_container">
<!-- DIV for TODO List -->
</div>
</div>

How do I save an HTML table edited with jQuery to local storage?

I have an html table that a user can add individual rows to. I would like the user to be able to save this offline so that the data on the table stays after a refresh. I have been told this is the easiest way but if anyone has any other suggestions I have open ears.
$(document).ready(function(){
var count = 1;
var table = "You fucked up yo";
$('#add').click(function addRow(){
var model = $('#Model').val();
var size = $('#Size').val();
var resolution = $('#Resolution').val();
var backlight = $('#Backlight').val();
var pins = $('#Pins').val();
var touch = $('#Touch').val();
$('#screens').append("<tr id='row"+count+"'><td>"+count+"</td><td id
='model"+count+"'>"+model+"</td><td id ='sizes"+count+"'>"+size+"</td><td
id
='resolution"+count+"'>"+resolution+"</td><td id
='backlight"+count+"'>"+backlight+"</td><td id ='pins"+count+"'>"+pins+"
</td><td id ='touch"+count+"'>"+touch+"</td>");
var key = "table"+count;
count++;
});
$('#remove').click(function removeRow(){
var row = $('#row').val();
$('table#screens tr#row'+row).remove();
});
$('#save').click(function save(){
var table = $('#screens').html;
localStorage.setItem("Table", table);
alert('yo');
});
$('#open').click(function open(){
$('#screens').html = localStorage.getItem("Table");
alert('yo');
});
});
Best way to solve this would be using a JSON to store your table values and just storing that structure in localStorage or database. But to answer your question I think this is what you need to store and retrieve the table structure from localStorage. Hope this is what you need.
<!DOCTYPE html>
<html>
<body>
<div id="tablediv"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("Mytable", "<table><tr><td>col1</td></tr></table>");
// Retrieve
document.getElementById("tableDiv").innerHTML = localStorage.getItem("Mytable");
} else {
document.getElementById("tableDiv").innerHTML = "Your browser does not support Web Storage";
}
</script>
</body>
</html>
You have the right idea. Be sure to use JSON.stringify() and JSON.parse() as follows:
var tableData = [{name: "John", email: "jhenry#example.com"}];
// Persist
localStorage.setItem("nameForYourData", JSON.stringify(tableData));
// Retrieve
tableData = JSON.parse(localStorage.getItem("nameForYourData"));
The easiest way to do this i think:
var table = $('table').wrap('<table/>').parent().html();
table = JSON.stringify(table);
window.localStorage.setItem('savedTable', table);
// then later
table = JSON.parse(window.localStorage.getItem('savedTable'))
Here's a fiddle: https://jsfiddle.net/8dhnqy0b/

How to get value from firebase database show in p element

I'm trying to create chat app using firebase database.
I have html:
<input type="text" name="txt" id="txt">
<button type="submit" id="btn-send" onclick="addElement()">SEND</button>
<p id="list-message"></p>
and javascript :
var rootRef = firebase.database();
var message = rootRef.ref().child('/message');
function addElement() {
var x = document.getElementById('txt').value;
var node = document.createElement("li");
var text = document.createTextNode(x);
node.appendChild(text);
document.getElementById('list-message').appendChild(node);
message.push().set({
Message: $("#txt").val()
});
}
Screenshot of my Firebase data
How can I retrieve all the data and show as a list in <p id="list-message"></p>?
Add a data listener which looks out for changes in the message node then update <p id="list-message"></p>.
message.on('child_added', function(snapshot) {
var msg = snapshot.val();
var msgDiv = document.createElement("div");
msgDiv.textContent = msg.Message;
document.getElementById("list-message").appendChild(msgDiv);
});
Refer to this codelab for more on how to build a chat app: https://codelabs.developers.google.com/codelabs/cloud-firebase-chat/.

Send Email Checkbox on Attendee Sublist user event script

In NetSuite I have a custom record for keeping track of our safety meetings, from the record, I have a user-event script, BEFORE SUBMIT FUNCTION, running to create an event record. On the Event record -> attendee sublist, I am able to add the attendees, but I am unable to set the sendemail checkbox. Any insight would be appreciated.
/*
user event script
before record submit
creates a new event record based off this safety meeting record.
*/
function createSafetyMeetingEventRec(type){
if(type=="create")
{
try
{
//get values from the safety meeting record
var altName = nlapiGetFieldValue('altname');
var message = nlapiGetFieldValue('custrecord53');
var local = nlapiGetFieldValue('custrecord56');
var date = nlapiGetFieldValue('custrecord51');
var time = nlapiGetFieldValue('custrecord52');
//name of the event record
var eventTitle = 'SM-' + altName;
//create the event record
var eventRec = nlapiCreateRecord('calendarevent');
//set the event record field values
eventRec.setFieldValue('title', eventTitle);
//script search for the Safety Committee group members in netsuite
var entitygroupSearch = nlapiSearchRecord("entitygroup",null,
[
["internalid","anyof","120147"]
],
[
new nlobjSearchColumn("entityid","groupMember",null),
new nlobjSearchColumn("internalid","groupMember",null)
]
);
//get who created the event, this user is automatically on the attendee list, and cannot be added again.
var eventUserSet = eventRec.getLineItemValue('attendee', 'attendee', 1);
for(var i = 0; i < entitygroupSearch.length; i++){
var newAt = eventRec.getLineItemCount('attendee') + 1;
var intIDuser = entitygroupSearch[i].getValue("internalid","groupMember",null);
if(intIDuser != eventUserSet){
eventRec.setLineItemValue('attendee', 'sendemail', newAt, 'T');
eventRec.setLineItemValue('attendee', 'attendee', newAt, intIDuser);
}else{
continue;
}
}
//set the resource calendar to Service Calendar, 3 is the internal id of the service calendar resource
var newAtResource = eventRec.getLineItemCount('resource') + 1;
eventRec.setLineItemValue('resource', 'resource', newAtResource, '3');
var eventId = nlapiSubmitRecord(eventRec, true);
}catch(err)
{
nlapiLogExecution("error","Error Creating Event Record From Safety Record ","Details: " + err.message);
}
}//end if
}
I think you also need
eventRec.setFieldValue('sendemail', 'T');
before the submit

Firebase "Uncaught TypeError: myDataRef.push is not a function"

I'm making PHP game, which uses Firebase-powered chat.
I have included code below. Its element of
$text = "(...)";
(where (...) means the code)
I have a problem, when I click Enter on the input to send the message nothing happens. Chrome shows that
Uncaught TypeError: myDataRef.push is not a function
but that makes no sense. My code is most copy of the Firebase Tutorial, but modified, that input is before the messages, and when new one appears it goes to up, not down.
<input type='text' id='messageInput' placeholder='Wiadomość'>
<div id='messagesDiv'></div><br>
<script>
var myDataRef = new Firebase('https://********.firebaseio.com/').limit(15);
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = '".$user->username."';
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);
});
myDataRef.on('child_removed', function(snapshot) {
//do nothing
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).prependTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
I have searched for any answers, but I haven't found anything.
Thanks
Note: the game is available here: Automaty, but its in Polish.
You are trying to write a transaction on a Query object.
var myDataRef = new Firebase('https://********.firebaseio.com/').limit(15);
The limit() returns a Query object and not a DatabaseReference.
Instances of Query are obtained by calling startAt(), endAt(), or limit() on a DatabaseReference.
Try:
var myDataRef = new Firebase('https://********.firebaseio.com/');
myQuery = myDataRef.limit(15);
// ...
myDataRef.push({name: name, text: text});

Categories