Display Firebase data previously/currently submitted - javascript

So I'm simply trying to make a page where I have an input for a user's name and age, then they submit that, and it sends that to the Firebase database, and that is working perfectly. The other thing I'm trying to do is display the data submitted in a "view" section. So just display the user's name and age below. I'm struggling to understand/get why my code is not working -- I have an h3 in place that should be replaced by the data that is stored in my database.
Here is my code for the retrieval section
'Age' is what one category of children is called (the other is 'Name')
<h2> View</h2>
<h3 id="showData"> Hello</h3>
<script>
showData = document.getElementByID('showData');
var firebaseDataRef = firebase.database().ref().child('Age');
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.value;
});
the rest of my code:
<input type=text" id="userName">
<input type="number" id="userAge">
<button id="btUpdateMessage" margin-bottom="20px" onclick="addFB()"> Update</button>
<script>
var lblCurrentMessage = document.getElementById('lblCurrentMessage'),
userName = document.getElementById('userName'),
btUpdateMessage = document.getElementById('btUpdateMessage'),
userAge = document.getElementById('userAge'),
rootRef = new Firebase('https://addview-c21e6.firebaseio.com'),
currentMessageRef = rootRef.child('Name'),
currentNameRef = rootRef.child('Age');
function addFB()
{
currentMessageRef.push(userName.value);
currentNameRef.push(userAge.value);
userName.value = '';
userAge.value = '';
}

.value is not a property of DataSnapshot. You need to call the .val() method on it.
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.val();
});
docs: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#val

Related

Compare Field Input with Firebase Entry

I have an HTML input field where the user needs to type in a specific 6-digit password (handed to the user at an exhibition). Attached to the password on Firebase is an ID psrID (see attached img below).
The ID <?= $page->psrID() ?> is also being used to generate different pages, fetch textures for objects from my CMS etc.
There is only 1 correct password per <?= $page->psrID() ?> available. I can console.log(seeds) to show me the whole array.
If equal = It should display a success message;
If not equal = It should display sth like «wrong password»
Here's how I get the data from Firebase:
var database = firebase.database();
var ref = database.ref();
ref.on('value', gotData, errData);
function gotData(data) {
var seeds = data.val();
console.log(seeds);
}
function errData(err) {
console.log('Error!');
}
And here is the HTML input form:
<form class='seedForm' method='post'>
<label for='seedPassword'></label>
<input id='seedPasswordInput' type='text' name='seedPWD' maxlength='6' class='button' onfocus="this.value=''" value='Enter Pasword' style='text-transform:uppercase' />
<input type='submit' name='button' class='button' value='Register' />
</form>
What function do I have to write to compare the password entered by the user to the password of the ID on Firebase? Thanks for your help!
If I understand you correctly, you want to only read child nodes where a specific property matches a certain value. In that case, you'll want to use a query:
var ref = database.ref();
var query = ref.orderByChild("password").equalTo("HYP4WJ");
query.on('value', gotData, errData);

Having problems storing and displaying info in google firebase

I am trying to make a chatroom where the messages are stored in google firebase. I have not learned Javascript yet, but my schoolbook contains all the necessary Javascript code that I need for the task. The chatroom will have two inputs, one for username and one for a message, and a button to send the message. My problem is that whenever I try to send the message it won't store itself in the firebase and thus not be displayed. I apologize for the IDs and classes being in Norwegian, but I'm afraid that if I try to change it I will mess up something in the process.
<form id="skjema">
<input type="text" id="inpAvsender" required placeholder="Brukernavn">
<input type="text" id="inpMening" required placeholder="Melding">
<button type="submit" class="button">Send</button>
</form>
<article id="txtMeldinger"></article>
// google firebase snippet here //
<script>
let database = firebase.database();
let meldinger = database.ref("meldinger");
let skjema = document.
getElementById("skjema");
let inpAvsender = document.
getElementById("inpAvsender");
let inpMening = document.
getElementById("inpMening");
let txtMeldinger = document.
getElementById("txtMeldinger");
function visMelding(snapshot) {
let melding = snapshot.val();
let meldingTekst ='<p>
<b>${melding.avsender}:</b>
<i>${melding.tekst}</i>
</p>';
txtMeldinger.innerHTML = txtMeldinger.
innerHTML + meldingTekst;
}
function regNyMelding(evt) {
evt.preventDefault();
var nyMelding = {
avsender: inpAvsender.value,
tekst: inpMening.value
};
meldinger.push(nyMelding);
inpMening.value ="";
}
meldinger.on("child_added", visMelding);
skjema.onsubmit = regNyMelding;
</script>

Retrieve multiple value from HTML input and store in JSON key, value[Array]

Good evening all!
I am currently working with google maps api.
The google maps asks for a json format to set directions.
Everything works fine if i make my own json object, but i would like to retrieve data from input fields and store it in the json object.
Right now i can retrieve 1 value from the input field and store it. But i woud like to retrieve multiple values. This is needed to set an direction on the maps. I need to find a way to store the multiple values in an json object as array. Correct my if i wrote some things wrong, i am not a expert :)
"key" : "Array"
See below for the example + Code
This is what i need to try to get:
A user comes to the page and sees 2 input fields, he fills in Amsterdam and Rome but he always needs Paris. So the user press the + icon. Another input field appears and he fills in Paris. when the user submits this below must be the json result from the input fields
"locatie" : ["Berlin", "Amsterdam", "Paris", "Rome"]
This is is my form:
<form onsubmit="return make_json(this);">
Locatie: <input type="text" name="locatie">
<input type="submit" name="" value="Make Trip">
</form>
My js function:
function make_json(form) {
var json = {
"locatie" : form.locatie.value
// this is what works and what i would like to retrieve from multiple input fields
//"locatie" : ["Paris", "Amsterdam"]
};
return json;
}
In the google maps api i call the function and use the json:
var jsonArray = make_json();
You can declare an array and push the values to it when the button is clicked.
// Declare location array
var locations = [];
// Button bindings
var locationButton = document.getElementById("addNewLocation");
locationButton.onclick = addNewLocation;
var displayJsonButton = document.getElementById("displayJsonObject");
displayJsonButton.onclick = displayJsonObject;
// Button functions
function addNewLocation() {
var location = document.getElementById("locationText").value;
locations.push(location);
document.getElementById("locationText").value = "";
}
function makeJsonObject() {
var json = {
location : locations
}
return json;
}
function displayJsonObject() {
var obj = makeJsonObject();
console.log(obj.location);
}
<input id="locationText" type="text" />
<button id="addNewLocation">Add</button>
<button id="displayJsonObject">Display JSON</button>
The results will be populated in the console. I have also returned the JSON object for you in the displayJsonObject() function, which you could use to pass to the API.
You can also try this, if you want to keep showing the locations entered before adding new location.
function addInput() {
var input = document.createElement('input');
input.setAttribute("type", "text");
input.setAttribute("name", "locatie[]");
inputs.appendChild(input);
}
function make_json() {
var form = document.querySelector("form");
var values = [];
var locations = form['locatie[]'];
if (locations.length) {
locations.forEach(function(input) {
values.push(input.value);
});
} else {
values.push(locations.value);
}
var json = {
"locatie": values
};
console.log(json);
return json;
}
<form>
Locatie:
<div id="inputs">
<input type="text" name="locatie[]">
</div>
<button onClick="addInput()">+</button>
<input type="submit" value="Make Trip" onClick="make_json(this)">
</form>
Note: Take care of UI. If user enters more number of inputs, UI may deform.

Resetting/Clearing Form Upon Button Click w/ Firebase

I'm having trouble actually clearing the content of a form upon button click with Firebase. I'm able to use type="reset"on another form I have that just has one text field, however, the second form has two text fields and when I try the following:
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
or I try this (something just using reset()):
function clearFields() {
document.getElementById(userCityEmail).reset();
document.getElementById(cityTextField).reset();
}
The page will reload but nothing is sent to the Firebase. If I don't use the above functions and leave the text within the text field, it sends the content to Firebase. Where am I going wrong? Thanks in advance!
Here's my HTML form:
<form id="myform" method="post">
<input type="email" class="contactUsEmail" id="userCityEmail" placeholder="Enter email" name="contactUsEmail">
<input type="text" class="contactUsEmail" id="cityTextField" placeholder="City" name="contactUsCity">
<button type="submit" id="citySubmitButton" onclick="submitCityClick(); clearFields(); return false;" class="btn btn-primary contactUsButton">Submit</button>
</form>
Javascript:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
var citySubmitButton = document.getElementById('citySubmitButton');
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push().set(userEmail);
}
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
Figured out what happened now.
The problem you had was that you were calling
firebaseRef.child("potentialCities").push().set(userEmail);
This doesnt make sense. Either use just push(userEmail) or set(userEmail).
The difference between these two things is that push will create a random ID under the potentialCities tree node, and set will put user email data right under the same object. It probably will be overwritten. Push is recomended for this case.
To explain the field clearing, still have the clearfields method in the submit click method. Code beneath
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push(userEmail);
clearFields()
}
This also expects that you have the right firebase ref, have you checked the url you are using?
Another thing you are doing wrong is that you are declaring these variables:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
Then trying to get the elementById, with that variable, in clearFields:
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
This doesnt work, you have to either get it by string in clearFields or just use the variable you declared:
userCityEmail.value = "";
or
document.getElementById('userCityEmail').value = "";
I would not recommend to just pull in jQuery just for that reason. It's a big library, and if you can suffice with vanilla javascript, do that!

Using form element as variable in Firebase .child()

I would like to use the value of an input from a form element to add a child reference to my firebase data. But, the firebase .child() requires a string, and I've tried to insert a variable (whose value is a string) but it won't work. How do I by pass this?
For example here is a very simple code of an input and submit button. On submission, I want to take the username and add a child reference to my database (under /users ref) in this structure:
{username:{userid: "someID"}}
<html>
<body>
<form>
<input id="testusername" type="text">
<button type="submit" id="testsubmit" value="submit"></button>
</form>
<p>test file for .child()/p>
<script type="text/javascript">
$('#testsubmit').on('click',function(){
var elusername = document.getElementById('testusername');
var username = elusername.value;
alert('username is' + username)
var url = "https://thriftit.firebaseio.com/users";
var firebaseRef = new Firebase(url);
firebaseRef.child(username).push({
userid: "someID"});
});
</script>
</body>
</html>
There's a couple of things.
You're submitting the form before the javascript can run, you need to prevent the page from submitting the page on the click, so remove the type="submit"
I wouldn't do a child on the username, reason being if another user with the same username adds some data, then it would be added under the same username so you'll get two lots of data under the same username.
You want to so something similar to this:
$('#testsubmit').on('click',function(){
var elusername = document.getElementById('testusername'),
username = elusername.value,
url = "https://thriftit.firebaseio.com/users",
firebaseRef = new Firebase(url);
userRef = firebaseRef.push({
username: username,
userid: "someID"
});
console.log(userRef.name()); // this is the uid for the newly generated user
});

Categories

Resources